Python3 File Methods
open() Method
The open()
method in Python is used to open a file and return a file object.
This function is essential for any file processing. If the file cannot be opened, an OSError
is thrown.
Note: It is crucial to ensure that the file object is closed using the close()
method after using the open()
method.
The common form of the open()
function accepts two parameters: the file name (file) and the mode (mode).
open(file, mode='r')
The complete syntax is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameter descriptions:
- file: Required, the file path (relative or absolute).
- mode: Optional, the file open mode.
- buffering: Sets the buffering policy.
- encoding: Typically uses UTF-8.
- errors: Error handling level.
- newline: Distinguishes newline characters.
- closefd: The type of the file parameter passed.
- opener: Sets a custom opener; the opener's return value must be an open file descriptor.
The mode parameter options are:
Mode | Description |
---|---|
t | Text mode (default). |
x | Write mode, creates a new file; if the file already exists, an error is raised. |
b | Binary mode. |
+ | Opens a file for updating (read and write). |
U | Universal newline mode (not supported in Python 3). |
r | Opens a file for reading. The file pointer is placed at the beginning. This is the default mode. |
rb | Opens a file in binary format for reading. The file pointer is placed at the beginning. This is the default mode for non-text files like images. |
r+ | Opens a file for both reading and writing. The file pointer is placed at the beginning. |
rb+ | Opens a file in binary format for both reading and writing. The file pointer is placed at the beginning. This is the default mode for non-text files like images. |
w | Opens a file for writing only. If the file already exists, it opens the file and starts editing from the beginning, deleting existing content. If the file does not exist, a new file is created. |
wb | Opens a file in binary format for writing only. If the file already exists, it opens the file and starts editing from the beginning, deleting existing content. If the file does not exist, a new file is created. This is the default mode for non-text files like images. |
w+ | Opens a file for both reading and writing. If the file already exists, it opens the file and starts editing from the beginning, deleting existing content. If the file does not exist, a new file is created. |
wb+ | Opens a file in binary format for both reading and writing. If the file already exists, it opens the file and starts editing from the beginning, deleting existing content. If the file does not exist, a new file is created. This is the default mode for non-text files like images. |
a | Opens a file for appending. If the file already exists, the file pointer is placed at the end. New content is written after existing content. If the file does not exist, a new file is created for writing. |
ab | Opens a file in binary format for appending. If the file already exists, the file pointer is placed at the end. New content is written after existing content. If the file does not exist, a new file is created for writing. |
a+ | Opens a file for both reading and writing. If the file already exists, the file pointer is placed at the end. The file opens in append mode. If the file does not exist, a new file is created for reading and writing. |
ab+ | Opens a file in binary format for appending. If the file already exists, the file pointer is placed at the end. If the file does not exist, a new file is created for reading and writing. |
The default is text mode; add b
for binary mode.
File Object
A file object is created using the open
function. Below is a table listing commonly used functions for file objects:
Number | Method and Description |
---|---|
1 | file.close() Closes the file. Operations like reading and writing are not possible after closing. |
2 | file.flush() Flushes the internal buffer, immediately writing buffered data to the file. |
3 | file.fileno() Returns an integer file descriptor, usable in low-level operations like those in the os module. |
4 | file.isatty() Returns True if the file is connected to a terminal device; otherwise, returns False . |
5 | file.next() The next() method is not supported in Python 3 for file objects. Returns the next line from the file. |
6 | file.read([size]) Reads the specified number of bytes from the file; if not specified or negative, reads all. |
7 | file.readline([size]) reads the entire line, including the "\n" character. |
8 | file.readlines([sizeint]) reads all lines and returns a list. If sizeint > 0 is given, it returns lines whose total size is approximately sizeint bytes. The actual read size may be larger than sizeint because it needs to fill the buffer. |
9 | file.seek(offset[, whence]) moves the file read pointer to the specified position. |
10 | file.tell() returns the current position in the file. |
11 | file.truncate([size]) truncates the file starting from the first line and first character, reducing the file to size characters. If no size is given, it truncates from the current position; subsequent characters are deleted, with a newline in Windows systems representing 2 characters. |
12 | file.write(str) writes a string to the file and returns the length of the written string. |
13 | file.writelines(sequence) writes a sequence of strings to the file. Newlines need to be added manually for each line. |