Writing to a file

Published

2023-08-02

Writing to a file

So far, the only output our programs have produced is characters printed to the console. This is fine, as far as it goes, but often we have more output than we wish to read at the console, or we wish to store output for future use, distribution, or other purposes. Here we will learn how to write data to a file.

With Python, this isn’t difficult. Python provides us with a built-in function open() which returns a file object. Then we can read from and write to the file, using this object.

The best approach to opening a file for writing is as follows:

with open('hello.txt', 'w') as f:
    f.write('Hello World!')

Let’s unpack this one step at a time.

The open() function takes a file name, an optional mode, and other optional arguments we don’t need to trouble ourselves with right now. So in the example above, 'hello.txt' is the file name (here, a quoted string), and 'w' is the mode. You may have already guessed that 'w' means “write”, and if so, you’re correct!

Python allows for other ways to specify the file, and open() will accept any “path-like” object. Here we’ll only use strings, but be aware that there are other ways of specifying where Python should look for a given file.

There are a number of different modes, some of which can be using in combination. Quoting from the Python documentation:1

Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)

Again, in the code snippet above, we specify 'w' since we wish to write. We could have written:

with open('hello.txt', 'wt') as f:
    f.write('Hello World!')

explicitly specifying text mode, but this is somewhat redundant. We will only present reading and writing text data in this text.2

The idiom with open('hello.txt', 'w') as f: is the preferred approach when reading from or writing to files. We could write

f = open('hello.txt', 'w')
f.write('Hello World')
f.close()

but then it’s our responsibility to close the file when done. The idiom with open('hello.txt', 'w') as f: will take care of closing the file automatically, as soon as the block is exited.

Now let’s write a little more data. Here’s a snippet from a poem by Walt Whitman (taking some liberties with line breaks):

fragment = ["Flood-tide below me!\n",
            "I see you face to face\n",
            "Clouds of the west--\n",
            "Sun there half an hour high--\n",
            "I see you also face to face.\n"]

with open('poem.txt', 'w') as fh:
    for line in fragment:
        fh.write(line)

Here we simply iterate through the lines in this fragment and write them to the file poem.txt. Notice that we include newline characters '\n' to end each line.

Writing numeric data

The .write() method requires a string, so if you wish to write numeric data, you should use str() or f-strings. Example:

import random

# Write 10,000 random values in the range [-1.0, 1.0)
with open('data.txt', 'w') as f:
    for _ in range(10_000):
        x = (random.random() - 0.5) * 2.0
        f.write(f"{x}\n")

Always use with

From the documentation:

Warning: Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

Since we can forget to call f.close(), use of with is the preferred (and most Pythonic) approach.

Comprehension check

  1. Try the above code snippets to write to files hello.txt and poem.txt.

  2. Write a program that writes five statements about you to a file called about_me.txt.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. https://docs.python.org/3/library/functions.html#open↩︎

  2. It is often the case that we wish to write binary data to file, but doing so is outside the scope of this text.↩︎