Python can open files in different modes like reading, write, append, etc. One of the most used mode is opening files for writing. But as a similar mode also append mode can be used to write by adding extra information without deleting previous data.
Open File For Writing
A file can be opened for writing by using the open() method. The open() method can be used to create a file and open it for writing. If the file already exists the file is opened for writing. The open() method accepts two parameters where the first one is the name of the file we want to open and the second one is the file open mode. The “w” is the write mode for the file.
f = open("mtfile.txt","w") f.write("Hi") f.close()
Open File For Appending
Another way to open the file to write is to append mode. Append mode is very similar to the write mode but the existing data can not be changed only new data can be appended. The append mode is specified with the “a” like below.
f = open("mtfile.txt","a") f.write("Hi") f.close()