Python write to file in append or truncate mode
Open the file in append mode or truncate mode can be set up by parameters like. Below you can find the most used ones:
- w - Fully Truncate file or create new file for writing.
- a - Open the file for writing ( create if does not exist ). Next writes of existing file are in append mode
- r - Open file in reading mode.
- b - opens the file in binary and append mode
There are some additional parameters like:
- r+ - Read or write
- w+ - Read or write ( create if doesn't exists otherwise truncate it )
- a+ - Open for reading and writing. ( create if doesn't exists otherwise append to it )
Example in append mode:
with open("/home/myfile.txt", "a") as myfile:
myfile.write("append this line")
Example in truncate mode:
with open("/home/myfile.txt", "w") as myfile:
myfile.write("this is the first line of the file")
Example in truncate binary mode:
with open("myimage.png", "wb") as img:
img.write(binary_data)
Some operations may require you to open the file in binary mode. When you need data as is without any transformations such as images, encodings etc