You can learn about Python File Processing Programs with Outputs helped you to understand the language better.

Python Programming – File Opening In Various Modes

The access mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. You specify the access mode of a file through the mode argument. You use ‘r’, to read the file, and use ‘w’ or ‘a’, to write or append, respectively. The mode argument if not passed, then Python will assume it to be V by default. Mode is an optional string that specifies the mode in which the file is opened. The mode you choose will depend on what you wish to do with the file. Table 11.1 shows the details about the access mode to open a file.

Access Mode

Description

r It opens the file for reading only. Starts reading from beginning of file. This is the default mode.
rb It opens the file for reading only in binary format. The file pointer exists at the begin­ning of the file.
r+ It opens the file for reading and writing both. The file pointer exists at the begin­ning of the file. If you want to open an existing file for read and write, you should better use “r+”, because this will not delete the content of the file.
rb+ It opens the file for reading and writing both in binary format. The file pointer exists at the beginning of the file.
X It creates a new file with the specified name. It causes an error when a file exists with the same name.
W It opens the file to write only. It will over­write the file if any file exists. The file pointer is at the beginning of the file.
Wb It opens the file to write only. It will over­write the file if any file exists. The file pointer is at the beginning of the file.
w+ It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
wb+ It opens the file to write and read both. It is different from r+ as it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.
a It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.
ab It opens the file in the append mode in binary format. The file pointer is at the end of the file if the file exists. If the file does not exist, it creates a new file for writing.
a+ It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. If the file does not exist, it creates a new file for reading and writ­ing.
ab+ It opens a file to append and read both in binary format. The file pointer remains at the end of the file if the file exists. If the file does not exist, it creates a new file for reading and writing.

Leave a Reply

Your email address will not be published. Required fields are marked *