Python open() Function – Perform Read/Write Operations in Files

A visual guide to learn file operations in Python using the 'open()' function. Discover reading, writing, and appending files

What is Python open() function?

In order to perform input/output (I/O) operations in files, you have to open a file.

The Python open() function is used to open the specified file where you may perform reading, writing, and other operations.

In this tutorial, I will show you how to open a file, read the content of a file, write to a file, and do other related things.

How to open files in Python?

The syntax of using the open() function is:

open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None)

The parameters of the open function are explained below:

Parameter Description
file Specifies the relative or absolute path to the file you want to open. An error (OSError) occurs if the file cannot be opened.
mode Specifies the purpose of opening the file, such as ‘r’ for reading, ‘w’ for writing, and ‘a’ for appending. Detailed mode options are provided in the last section.
buffering Sets buffering on or off, using an Integer value. 1 enables text-mode line buffering, and 0 disables buffering in binary mode. This parameter is optional. The default buffering policy is applied if not provided.
newline Applies to text-mode only and specifies universal newlines. Valid values include ‘\n’, ‘\r’, ‘\r\n’, None, and ”.

An example of reading a file by read method of open() function

In this example, a text file is opened in read-only mode by using the ‘r’ value for the mode parameter in Python open() file function.

The text of the readme.txt file is displayed on the screen.

The readme.txt file is placed at the same location where the Python source file is placed:

# The example of open() functio for reading a text file

objFile = open("readme.txt", "r")

fileContent = objFile.read();

print ("The text file contains: : ", fileContent)


# After performing the operation, close the file

objFile.close()

Python open

The following things should be noted in the program:

  • First of all, the file object is created, and the open() function is used.
  • In the open() function, the relative path is given for the readme.txt file.
  • The mode parameter is ‘r’, which means opening the file in read-only mode.
  • The file content is read by using the Python read() method of the open() function.
  • The print function displayed the content of the file.
  • Finally, the close() function is used for closing the file.

The example of write to file by write() method

The following example shows using the Python write() method after creating a file object.

In the open() function, the ‘w’ parameter is given for the mode argument.

This enables us to write in a text file, however, the text file will be truncated while using this value. That means the existing text will be removed.

To demonstrate that, the content in the “readme.txt” file initially is “Hello World Python”. This is displayed before opening the file in read-only mode.

After that, the file is opened again in write-only mode, and the write() method is used for adding new text.

The file is closed again and reopened in read-only mode for displaying the content:

# The example of open() functio for reading a text file


objRead1 = open("readme.txt", "r")

ContFile = objRead1.read();

print ("Content before write() : ", ContFile)

# Closing the first instance

objRead1.close()


#Opening again for write to file

objWrite = open("readme.txt", "w")

objWrite.write ("Using 'w' for writing text in file")


#Closing the file in write mode

objWrite.close()


#Openging the file again for displaying content after writing

objRead2 = open("readme.txt", "r")

ContAfterWrite = objRead2.read();

print ("The content after write() : ", ContAfterWrite)


objRead2.close()

Python write

You can see, the initial text is truncated as we opened the file in write-only mode. The second print function displays only the newly written text.

Using the append mode example

If you require keeping the initial text and avoid truncating this while writing to file then you may use the file append mode.

For that, use the ‘a’ value for the mode parameter. This will append the new text to the end of existing content.

See this example where a few changes are made in the above example. The file text before and after writing the new text is displayed and you can see the difference.

# The example of append mode

objRead1 = open("readme.txt", "r")

ContFile = objRead1.read();

print ("Content before appending text : ", ContFile)


# Closing the first instance

objRead1.close()

#Open file in append mode

objAppend = open("readme.txt", "a")

objAppend.write ("Please dont remove the text..\nJust add ahead of existing text! Thanks")

#Closing the file in append mode

objAppend.close()

#Open and read after append(0

objRead2 = open("readme.txt", "r")

ContAfterAppend = objRead2.read();

print ("The content after append() : ", ContAfterAppend)


objRead2.close()

append text open

The new content is added ahead of the existing text. The newline ‘\n’ is used for writing text in the next line.

Reading only limited characters in the text file example

In all the above examples, the complete content of the text file is read and displayed by using the open() function’s read() method. If you require only a part of the text from the file then you may specify the size in the read() method as follows:

# Read file with size


objFile = open("readme.txt", "r")

fileContent = objFile.read(10);

print ("Reading limited data: ", fileContent)


objFile.close()

The output:

Reading limited data:  Python Hel

>>>

By default, the entire content is read and returned (if size is left as in the above examples).

Also, note that the returned data is either string for the text files and bytes object for binary mode.

Python read line-by-line example

You may use a for loop to loop over a file object for reading line by line. Have a look at this example where I wrote a few lines of text in the readme.txt file:

# Read file line by line

objFile = open("readme.txt", "r")

for linebyline in objFile:

    print(linebyline, end = '')

objFile.close()

The output:

Line 1- Python is cool

Line 2- Python is Great

Line 3- Python is Awesome

Line 4- Love it!!!

This way of reading line by line is memory efficient and fast.

An example of readline() method to read line by line

The readline() method can also be used for reading a single line from the file. In that case, the new line character is left at the end of the string. The new line is omitted at the last line.

# Read file readline()

objFile = open("readme.txt", "r")

print (objFile.readline());

print (objFile.readline());


objFile.close()

The Output:

readline

Reading all lines in a list example

You may also read all lines in a file to the list. See the example below:

# Read file in list example

objFile = open("readme.txt", "r")

a_list = list(objFile)


print (a_list)

objFile.close()

The output:

[‘Python\n’, ‘Read\n’, ‘Write\n’, ‘Read\n’, ‘Open\n’, ‘Close\n’, ‘\n’]

List of modes

Mode Description
‘r’ Default mode for reading a text file. Allows reading but not writing to the file.
‘r+’ Opens the file in both read and write mode, allowing reading and writing to the file.
‘w’ Opens a text file in write-only mode. It truncates the content of the file, creating an empty file or overwriting the existing one.
‘rb’ Opens the file in binary format for reading only. Used for reading binary data like images or executables.
‘rb+’ Binary mode that allows both reading and writing. Suitable for modifying binary files.
‘wb’ Opens the file in binary write-only mode. Creates a new binary file or overwrites an existing one.
‘a’ Creates a new file if it doesn’t exist. Opens it in append mode for writing at the end of the file, preserving existing content.
‘a+’ Opens the file for both reading and appending. Allows reading the existing content and appending new data at the end.

Useful related reading: The with keyword as doing I/O operations in files.<.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!