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 file operations such as reading and writing, you first need to open the file using the open() function. If the file does not exist, the open() method returns a "FileNotFoundError" exception.

File Opening Modes

The following are the different file opening modes that are used with the open() function to open a file:

  • 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.

open() Function Examples

Practice the following examples to understand the use of open() function in Python:

Example: Open File in Read Mode Using open() Function

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: Open File in Append Mode Using open() Function

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: Open Binary File in Read Mode Using open() Function

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