Python File Open Modes

We should use open() function to open a file. This function accepts 'filename' and 'open mode' in which to open the file.

file handler = open("file name", "open mode")

Here, the 'file name' represents a name on which the data is stored. We can use any name to reflect the actual data. For example, we can use 'empdata' as file name to represent the employee data. The file 'open mode' represents the purpose of opening the file.

Different Modes to open a file

File open mode Description
w To write data into file.If any data is already present in the file, it would be deleted and the present data will be stored
r To read data from the file. The file pointer is positioned at the beginning of the file.
a To append data to the file. Appending means adding at the end of existing data. The file pointer is placed at the end of the file. If the file does not exist, it will create a new file for existing data.
w+ To write and read data of a file. The previous data in the file will be deleted.
r+ To read and write data into a file. The previous data in the file will not be deleted.
a+ To append and read data of a file. The file pointer will be 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.