Python, how to write to a file

By

Learn how to write to a file in Python using open() with append or write mode, then the write() and writelines() methods, and remember to close the file.

~~~

To write content to a file, first you need to open it using the open() global function, which accepts 2 parameters: the file path, and the mode.

You can use a as the mode, to tell Python to open the file in append mode and add content to the file

filename = '/Users/flavio/test.txt'

file = open(filename, 'a')

#or

file = open(filename, mode='a')

Or you can use the w flag to clear the existing content:

filename = '/Users/flavio/test.txt'

file = open(filename, 'w')

#or

file = open(filename, mode='w')

Be careful with w. The file is truncated the moment you open it, not when you write. Open an existing file in w mode and its old content is already gone, even if you write nothing.

Both modes create the file if it doesn’t exist, so you don’t need to check for that first.

Writing content

Once you have the file open, you can use the write() and writelines() methods.

write() accepts a string.

writelines() accepts a list of strings:

filename = '/Users/flavio/test.txt'

file = open(filename, 'w')

file.write('This is a line\n')

file.writelines(['One\n', 'Two'])

file.close()

\n is a special character used to go to a new line

After running this, the file contains:

This is a line
One
Two

Notice that writelines() does not add newlines between the items. The name suggests it writes lines, but it just writes the strings one after the other. If you want each one on its own line, add \n at the end of each string yourself, like I did with 'One\n'.

Also note that write() returns the number of characters written. You can usually ignore it, but it explains the number you see when calling it in the Python REPL.

Remember to close a file after writing to it, using the file’s close() method. Python buffers writes for performance, so until the file is closed (or flushed) some of your content might not be on disk yet.

A better way to close files

Forgetting close() is the classic mistake with file writing. The fix is the with statement:

with open('/Users/flavio/test.txt', 'w') as file:
    file.write('This is a line\n')

with closes the file automatically when the block ends, even if an error happens in the middle. There’s nothing to forget.

One more mode worth knowing: x opens the file for exclusive creation. It behaves like w, but raises a FileExistsError if the file already exists. Use it when overwriting an existing file would be a bug.

Tagged: Python · All topics
~~~

Related posts about python: