Python pt.7 ‐ Filing - mattl1598/Project-Mochachino GitHub Wiki

Python text files:

Initialisation

file object = open(file_name, [access_mode], [buffering])

file_name: filepath of file to access or create

access mode: determines the mode in which the file will be opened

buffering: allows to computer to read data into a buffer in order to speed up access. default is fine

Access Modes

Mode Basic Text Complex
r read only Text Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb read only Binary Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ reading and writing Text Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
rb+ reading and writing Binary Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
w writing only Text Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb writing only Binary Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ reading and writing Binary Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ reading and writing Binary Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a appending Text Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab appending Binary Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ appending and reading Text Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ appending and reading Binary Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.