How to Write to Files in Python

Writing to files is an essential part of programming in Python. When working with data it is common practice to save it to files in various formats including as comma-separated-values or JSON for future use.

 

In this tutorial, we will learn how to write to files in Python with examples.

 

Writing to a File

To write to a file we can use the open() function, passing the path of the file as the first argument and the mode as the second. Since we want to write to the file the mode will be 'w' for write (don't worry if the file doesn't already exist as open() will automatically create one.) Then use the write() method on the file object, passing the data to use inside the () (parenthesis).

 

text = 'This is some text.'

with open('test.txt', 'w') as f:
    f.write(text)

 

You can write the same function above slightly differently by storing the file object as a variable, writing to it and then closing the file.

 

text = 'This is some text.'

file = open('test.txt', 'w')
file.write(text)
file.close()

 

Personally, I always use the first option as I think it looks cleaner having the write operation contained inside one function.

 

note - make sure you are not unintentionally overwriting an existing file as Python will simply wipe its existing data.

 

Read more about how to create/delete files and directories in Python.

 

Append Data to a File

We can write data to the end of a file without changing the existing data by putting the open() function in 'a' (append) mode.

 

text = 'This is some more text.'

with open('test.txt', 'a') as f:
    f.write(text)
This is some text.This is some more text.This is some more text.

 

As you can see in the output from the example above, the new data is appended directly to the end of the existing data. It might be better appending data on a new line using \n or with a leading   (space).

 

text = '\nThis is some more text.'

with open('test.txt', 'a') as f:
    f.write(text)
This is some text.
This is some more text.
This is some more text.

 

Don't Overwrite a File if it Exists

To check if a file exists and don't overwrite it if there is already one, put the open() function in 'x' mode. If a file with the same name exists it will throw a FileExistsError error, therefore, it should be put in a try except block so we can print the error.

 

text = 'This is some text.'

try:
    with open('test.txt', 'x') as f:
        f.write(text)
except FileExistsError as e:
    print(e)
[Errno 17] File exists: 'test.txt'

 

Write a List to a File

To write iterables to a file we can use the writelines() method of the open() function. It works by iterating through the list and appending each value to the file.

 

items = ['h', 'e', 'l', 'l', 'o']

with open('test.txt', 'w') as f:
    f.writelines(items)
hello

 

Conclusion

You now know how to create and write to files in Python in three different ways for different scenarios.

write file append