Write to a file in Python

Share
Copied to clipboard.
Series: Files
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read Watch as video Python 3.8—3.12

How can you write to a file in Python? And how can you create new files?

Let's talk about using Python's file write mode for writing to a file.

Files can be read (but not written) by default

Here we're using the open function on a text file called my_file.txt (using a with block to automatically close the file when we're done working with it) and we're calling the write method on the file object we get back to write text to that file:

>>> with open("my_file.txt") as f:
...     f.write("This is text!")
...     f.write("And some more text")
...

When we run this code, we'll see an error:

>>> with open("my_file.txt") as f:
...     f.write("This is text!")
...     f.write("And some more text")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

We get an error because Python's open function accepts more than just a filename:

>>> help(open)

Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd
=True, opener=None)

The open function also accepts a mode, and by default, that mode is r (for read mode). With this default mode, we can read from a file in Python, but not write to it.

In order to write text to this file, we need to specify write mode.

To write to a file we need to open our file in write mode

Here we can see the modes accepted by open function:

    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================

The default mode is r, in fact, more explicitly it's rt, for read text mode. We need to specify the mode as w or (even more explicitly) wt for write text mode (we want text mode as opposed to binary mode).

We're going to specify a mode (wt) as we open up our file:

>>> with open("my_file.txt", mode="wt") as f:
...     f.write("This is text!")
...     f.write("And some more text")

Notice that we're not passing our mode in as a positional argument, even though we could:

>>> with open("my_file.txt", "wt") as f:

We're passing mode as a named argument to be explicit.

When we open this file now and call its write method, we'll get back the number of characters that were written to this file:

>>> with open("my_file.txt", mode="wt") as f:
...     f.write("This is text!")
...     f.write("And some more text")
...
13
18

Newline characters aren't automatically added to the end of each line

If we take a look at the file contents of my_file.txt now, we'll see that our text was written to the file:

This is text!And some more text

But it wasn't written exactly how we wanted! We wanted to write two separate lines to this file, but instead, Python wrote just one line.

Python wrote just one line because it wrote exactly the text we gave to it, and we didn't give it any newline characters (\n) to write.

To write two separate lines to this file, we should end each of our lines in a newline character:

>>> with open("my_file.txt", mode="wt") as f:
...     f.write("This is text!\n")
...     f.write("And some more text\n")

Now as expected, we have two separate lines in this file:

This is text!
And some more text

Python doesn't write until the file is closed (or flushed)

Let's open a file without using a with block:

>>> f = open("my_file.txt", mode="wt")

And then call the write method on our file object to write some text to this file:

>>> f.write("some text")
9

Has our file been written to at this point? What's your guess? 🤔

The answer is, probably not! Our file is empty right now:


Python doesn't write to a file until the file is flushed or closed:

>>> f.flush()
>>> f.close()

The best way to make sure that everything will be written to your file as soon as you're done working to it is to use a with block to use your file as a context manager. This will make sure your file is closed automatically as soon as you're done working with it.

Use open with mode='wt' to write to a file

To write to a text file in Python, you can use the built-in open function, specifying a mode of w or wt. You can then use the write method on the file object you get back to write to that file.

It's best to use a with block when you're opening a file to write to it.

Concepts Beyond Intro to Python

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I'll share ideas new Pythonistas often overlook.