Python Tutorial Python Advanced Python References Python Libraries

Python open() Function



The Python open() function is used to open a file and returns it as a file object. It takes two parameters - filename and mode. See the syntax below:

Syntax

open(filename, mode)

Parameters

filename Required. specify filename with path which need to be opened.
mode Optional. specify mode of opening the file. default is read mode for text file that is "rt".

The different modes of opening a file are mentioned below:

ModeDescription
rDefault value. Opens a file for reading only. Raise an exception if the file does not exist.
r+Opens a file for reading and writing. Raise an exception if the file does not exist.
wOpens a file for writing only. Creates the file if it does not exist.
w+Opens a file for reading and writing. Creates the file if it does not exist.
aOpens a file for appending only. Creates the file if it does not exist.
a+Opens a file for appending and reading. Creates the file if it does not exist.
xCreates the specified file. Raise an exception if the file already exists.
x+Creates the specified file and Opens the file in reading and writing mode. Raise an exception if the file already exists.

Apart from this, the file can be handled as binary or text mode

ModeDescription
tDefault value. Opens a file in the text mode.
bOpens a file in the binary mode.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, open() function is used to open the file in "rt" mode which is read text mode. The "rt" mode is also the default mode and hence not required to specify.

MyFile = open("test.txt", "rt")

# is equivalent to
MyFile = open("test.txt")

The below code can be used to open test.txt file to read its content.

MyFile = open("test.txt", "r")
print(MyFile.read())

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ Python Built-in Functions