Python Writing Files

To write to a file in Python, you need to open the file in either write or append mode.

ModeDescription
wFile is opened in write mode. If file does not exist, a new file is created. If file exists, it is truncated to zero length and overwritten.
aFile is opened in append mode. If the file does not exist, a new file is created. If the file exists, new data is appended to the end of the file. Unlike write mode, the file is not truncated to zero length in append mode.

Append Mode

Consider we have the following file:

demo_file.txt
This is a test file
for demonstrating read()
function in Python.

The following code shows how to write to this file in append mode.

with open("demo_file.txt", "a") as f:
    f.write("--New content is added.")

After writing in append mode demo_file.txt is updated as follows:

demo_file.txt
This is a test file
for demonstrating read()
function in Python.--New content is added.

Write Mode

If we write to demo_file.txt in write mode, the file will be truncated to zero length and original content will be overwritten.

with open("demo_file.txt", "w") as f:
    f.write("--New content is added.")

After writing in append mode demo_file.txt is updated as follows:

demo_file.txt
--New content is added.
SHARE