Python open() Function



The Python open() function is a built-in function that is used to open a file and return its corresponding file object. To perform operations like reading or writing on a particular file, we first need to open it.

If the file cannot be found due to any reason, a "FileNotFoundError" exception will be raised.

The open() function is used in different modes, depending on the requirements −

  • r − It will open the file in read-only mode.

  • w − It is used when we want to write and truncate the file.

  • x − It is used for creating a file. If the file already exists an error will be thrown.

  • a − Opens a file for appending text at the end.

  • b − It specifies the binary mode.

  • t − It specifies the text mode.

  • + − Opens a file for updating.

Syntax

The syntax of the Python open() function is as follows −

open(file, mode)

Parameters

The Python open() function accepts two parameters −

  • file − This parameter represents path or name of the file.

  • mode − It indicates the mode in which we want to open the file.

Return Value

The Python open() function returns a file object.

Examples

Let's understand how open() function works with the help of some examples −

Example 1

The following example shows how to use the Python open() function. Here, we are opening a file in readonly mode and printing its content.

with open("newFile.txt", "r") as file:
   textOfFile = file.read()
   print("The file contains the following code:") 
   print(textOfFile)

When we run above program, it produces following result −

The file contains the following code:
Hi! Welcome to Tutorialspoint...!!

Example 2

When we open a file in append mode, which is signified by "a", the file allows us to append text to it. In the code below, we are opening a file to write text to it.

with open("newFile.txt", "a") as file:
   file.write("\nThis is a new line...")

file.close()
with open("newFile.txt", "r") as file:
   textOfFile = file.read()
   print("The file contains the following text:") 
   print(textOfFile)

Following is an output of the above code −

The file contains the following text:
Hi! Welcome to Tutorialspoint...!!

This is a new line...

Example 3

We can also read and convert the text of files into binary format. We need to specify the mode for this operation as "rb". The code below demonstrates how to read content of a given file in binary format.

fileObj = open("newFile.txt", "rb")
textOfFile = fileObj.read()
print("The binary form of the file text:") 
print(textOfFile)

Output of the above code is as follows −

The binary form of the file text:
b'Hi! Welcome to Tutorialspoint...!!\r\n\r\nThis is a new line...'
python_built_in_functions.htm
Advertisements