How to open a file, read data from the opened file, and write data to the file? In this article, we would discuss that in detail.
How to open a file in Python?
In Python, we can use the open() function to open a file. Though the open() function can take many arguments, most often we use two arguments with this function. The first argument is the filename and the second argument is the mode.
open("abc.txt", "w")
Here, the file “abc.txt” is opened in the write mode. There can be several modes with which a file can be opened. For example,
- r – open file in read mode
- w – open file in write mode
- r+ – open file for both reading and writing. If the file exists, the file pointer will point to the beginning of the file
- w+ – open file for both reading and writing. If the file exists, the new file will overwrite the existing one.
- a – open file in append mode
- a+ – open file for both reading and writing. If the file exists, the file pointer will point to the end of the file
- rb – rb mode is used to read binary data from a file
- wb – wb mode is used to write binary data to a file
- ab – open a file in append mode so that one can append binary data to the file
- ab+ – open a file for both reading binary data and append binary data. If the file exists, the file pointer will point to the end of the file.
As per the Python documentation, it is always advisable to open a file like the following:






0 Comments