Skip to main content

open()

The open() function in Python is a built-in function used to open a file and return a corresponding file object. It takes two arguments: the file path and the mode in which the file should be opened (e.g., 'r' for reading, 'w' for writing). The open() function allows for reading, writing, or both, depending on the mode specified.

Parameter Values

Parameter Description
file

A path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

mode

A string indicating how the file is to be opened: 'r' for reading, 'w' for writing (truncating an existing file), 'x' for exclusive creation, 'a' for appending, 'b' for binary mode, 't' for text mode, '+' for updating (reading and writing).

buffering

An optional integer used to set the buffering policy.

encoding

An optional string specifying the encoding used to read or write the file.

errors

An optional string specifying how encoding and decoding errors are to be handled.

newline

An optional string specifying how newlines are handled.

Return Values

The open() function returns a file object, which can be an iterator for lines in the file.

How to Use open() in Python

Example 1:

The open() function is used to open a file and return a corresponding file object.

file = open('example.txt', 'r')
content = file.read()
file.close()
Example 2:

It can also be used with different modes such as 'w' for write or 'a' for append.

file = open('data.csv', 'w')
file.write('Name, Age\nJohn, 25\nAmy, 30')
file.close()
Example 3:

You can specify the encoding of the file when using open() by including the 'encoding' parameter.

file = open('file.txt', 'r', encoding='utf-8')
content = file.read()
file.close()