Python open() function

The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised.



file It represents the path and name of the file

mode It defines the string mode in which you want to open the file. The different modes are as follow:




open for reading (default)


open for writing, truncating the file first


open for exclusive creation, failing if the file already exists


open for writing, appending to the end of the file if it exists


Binary mode


Text mode(default)


open a disk file for updating (reading and writing)

buffereing This parameter is used for setting the buffering policy, and by default, its value is 1.

encoding It signifies the name of the encoding i.e to encode or decode the file.

errors This parameter represents a string specifying how to handle encoding/decoding errors.

newline This parameter determines how newlines mode works (available values: None, ‘ ‘, ‘\n’, ‘r’, and ‘\r\n’).

closefd This parameter must be True (default) else an exception will be raised.

opener This parameter represents a custom opener which returns an open file descriptor.


This function returns a file object which can be used to read, write and modify a file.

Example 1



Pin It on Pinterest

Share This