Open In App

Open a File in Python

Last Updated : 04 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s).

  • Text files: In this type of file, each line of text is terminated with a special character called EOL (End of Line), the new line character (‘\n’) in Python by default. In the case of CSV(Comma Separated Files, the EOF is a comma by default.
  • Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language, i.e., 0 and 1 format.

Refer to the below articles to get an idea about the basics of file handling.

Example:

gfg.txt

Hello! This is GeeksforGeeks 

In this example, we are using the open() function to read a file named gfg.txt and print its content in the terminal.

Python3
file1 = open("gfg.txt")

# Reading from file
print(file1.read())

file1.close()

Output:

Hello! This is GeeksforGeeks 

Opening a File in Python

Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).

Syntax of open() Function

File_object = open(“File_Name”, “Access_Mode”)

Parameters:

  • File_Name: This is the name of the file you want to open.
  • Access_Mode: This specifies the mode in which the file will be opened.

Note: The file should exist in the same directory as the Python script, otherwise full address of the file should be written. If the file is not exist, then an error is generated, that the file does not exist.

myfile.txt

Welcome to GeeksforGeeks!!

In the below example, we are using open() function to open a file in Python. Here, we have created a file object named file1 that we will use in further examples to read and write inside this file.

Python3
file1 = open("myfile.txt")

Access Modes of open() Function in Python

File modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The file handle is like a cursor, which defines where the data has to be read or written in the file. There are 6 access modes in Python.

Mode

Description

‘r’Open text file for reading. Raises an I/O error if the file does not exist.
‘r+’Open the file for reading and writing. Raises an I/O error if the file does not exist.
‘w’Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘w+’Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘a’Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘a+’Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘rb’Open the file for reading in binary format. Raises an I/O error if the file does not exist.
‘rb+’Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist.
‘wb’Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘wb+’Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘ab’Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.
‘ab+’Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.

Opening a File in Read Mode in Python

In this example, we are reading data from a Txt file. We have used read() to read the data.

Python3
file1 = open("myfile.txt")

# Reading from file
print(file1.read())

file1.close()

Output:

Welcome to GeeksForGeeks!!

Note: In the above example, we haven’t provided the access mode. By default, the open() function will open the file in read mode, if no parameter is provided.

Writing to an Existing File in Python 

If you want to add more data to an already created file, then the access mode should be ‘a’ which is append mode, if we select ‘w’ mode then the existing text will be overwritten by the new data.

Python3
file1 = open("myfile.txt", "a")

# Writing to file
file1.write("\nWriting to file:)")

# Closing file
file1.close()

Output:

Welcome to GeeksforGeeks!!
Writing to file :)

Opening a File with Write Mode in Python

In this example, we are using ‘w+’ which deleted the content from the file, writes some data, and moves the file pointer to the beginning.

Python3
# Open a file for writing and reading
file = open('test.txt', 'w+')

# Write some data to the file
file.write('Hello, world!')

# Move the file pointer back to the beginning of the file
file.seek(0)

# Read the data from the file
data = file.read()

# Print the data to the console
print(data)

# Close the file when you're done
file.close()

Output:

test.txt

Hello, world!

Read Line by Line Using readline() and open() Function

The readline() method in Python is used to read a single line from a file that has been opened for reading. When readline() is used in the code, it reads the next line of the file and returns it as a string.

test.txt

Welcome to GeeksforGeeks1
Welcome to GeeksforGeeks2
Welcome to GeeksforGeeks3
Welcome to GeeksforGeeks4
Welcome to GeeksforGeeks5
Welcome to GeeksforGeeks6-100
Welcome to GeeksforGeeks7
Welcome to GeeksforGeeks8
Welcome to GeeksforGeeks9
Welcome to GeeksforGeeks10

In this example, we are reading data line by line from a file named test.txt and printing it into the terminal.

Python3
# Open a file for reading
file = open('test.txt', 'r')

# Read the first line of the file
line = file.readline()

# Loop through the rest of the file and print each line
while line:
    print(line)
    line = file.readline()

# Close the file when you're done
file.close()

Output:

Welcome to GeeksforGeeks1
Welcome to GeeksforGeeks2
Welcome to GeeksforGeeks3
Welcome to GeeksforGeeks4
Welcome to GeeksforGeeks5
Welcome to GeeksforGeeks6-100
Welcome to GeeksforGeeks7
Welcome to GeeksforGeeks8
Welcome to GeeksforGeeks9
Welcome to GeeksforGeeks10

Opening a Python File Using with…open()

We can also use open() function and with keyword to open a file in Python.

example.txt

Hello GeeksforGeeks!!

In this example, we have used open() and with to open a file and print it’s content.

Python3
# Open a file in read mode

file_path = "example.txt"
with open(file_path, "r") as file:
    data = file.read()
    print(data)

Output:

Hello GeeksforGeeks!!


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads