open()
Method
The Python open()
method is used to open a file and return a file object.
During file processing, you will need to use this function, and if the file cannot be opened, it will raise an OSError
.
Note: When using the
open()
method, ensure that you close the file object by calling theclose()
method.
The common usage of the open()
function takes two parameters: the file name (file
) and the mode (mode
).
open(file, mode='r')
Complete Syntax:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameter Explanation:
file: Required. The path of the file (either relative or absolute).
mode: Optional. The mode in which the file is opened.
buffering: Optional. Sets buffering policy.
encoding: Optional. Specifies the encoding. Typically, this is set to
utf8
.errors: Optional. Sets the error handling strategy.
newline: Optional. Controls how universal newlines mode works.
closefd: Optional. Specifies whether to close the file descriptor after file closing.
opener: Optional. A custom opener that must return an open file descriptor.
File Opening Modes:
Mode | Description |
---|---|
t | Text mode (default). |
x | Write mode. Creates a new file, and raises an error if it already exists. |
b | Binary mode. |
+ | Opens a file for updating (reading and writing). |
U | Universal newline mode (no longer supported in Python 3). |
r | Opens a file for reading (default). The pointer is placed at the beginning. |
rb | Opens a file for reading in binary format. The pointer is placed at the beginning. Typically used for non-text files like images. |
r+ | Opens a file for reading and writing. The pointer is placed at the beginning. |
rb+ | Opens a file for reading and writing in binary format. The pointer is placed at the beginning. Typically used for non-text files like images. |
w | Opens a file for writing. If the file already exists, it truncates the file to zero length. If the file doesn’t exist, it creates a new file. |
wb | Opens a file for writing in binary format. If the file already exists, it truncates it. If the file doesn’t exist, it creates a new file. Typically used for non-text files like images. |
w+ | Opens a file for reading and writing. If the file already exists, it truncates it. If the file doesn’t exist, it creates a new file. |
wb+ | Opens a file for reading and writing in binary format. If the file already exists, it truncates it. If the file doesn’t exist, it creates a new file. Typically used for non-text files like images. |
a | Opens a file for appending. The pointer is placed at the end of the file. If the file doesn’t exist, it creates a new file. |
ab | Opens a file for appending in binary format. The pointer is placed at the end of the file. If the file doesn’t exist, it creates a new file. |
a+ | Opens a file for reading and appending. The pointer is placed at the end of the file. If the file doesn’t exist, it creates a new file. |
ab+ | Opens a file for reading and appending in binary format. The pointer is placed at the end of the file. If the file doesn’t exist, it creates a new file. |
The default mode is text mode (t
). If you need to open a file in binary mode, add the b
flag.
File Object
A file object is created using the open
function. The table below lists common methods used with file objects:
No. | Method & Description |
---|---|
1 | file.close() : Closes the file. After closing, the file cannot be read or written. |
2 | file.flush() : Flushes the internal buffer, writing the buffer data to the file immediately. |
3 | file.fileno() : Returns an integer file descriptor (FD), which can be used with low-level operations like os.read() . |
4 | file.isatty() : Returns True if the file is connected to a terminal device, otherwise returns False . |
5 | file.next() : In Python 3, the file object does not support next() for iteration. Instead, use for loops or __next__() . |
6 | file.read([size]) : Reads and returns the specified number of bytes from the file. If size is omitted or negative, it reads the entire file. |
7 | file.readline([size]) : Reads a single line from the file, including the newline character (\n ). |
8 | file.readlines([sizeint]) : Reads all lines from the file and returns them as a list. If sizeint > 0 , it reads lines approximately totaling sizeint bytes. |
9 | file.seek(offset[, whence]) : Moves the file pointer to a specified position. |
10 | file.tell() : Returns the current position of the file pointer. |
11 | file.truncate([size]) : Truncates the file to size characters. If size is omitted, the file is truncated at the current pointer position. |
12 | file.write(str) : Writes the string to the file and returns the number of characters written. |
13 | file.writelines(sequence) : Writes a list of strings to the file. If newline characters are needed, they must be added to each string manually. |