Sentry Answers>Python>

Write one or more lines to a file in Python

Write one or more lines to a file in Python

David Y.

The ProblemJump To Solution

What is the correct way to write lines to a file in Python?

The Solution

The standard way to write a single line to a file in Python 3 is as follows:

Click to Copy
with open('my_file.txt', 'a') as f: f.write('A new line.\n')

First, we use a with statement to wrap our write actions between the file’s opening and closing. This is a more succinct and Pythonic way of writing the following:

Click to Copy
f = open('my_file.txt', 'a') f.write('A new line.\n') f.close()

Using with means we don’t have to remember to close the file after writing to it.

We use Python’s open() function to open the file and create a corresponding file object, f. The second argument specifies the opening mode. Files can be opened in a number of different modes, most commonly 'r' for reading and 'w' for writing. The mode we’ve used here, 'a', is short for append. It is similar to opening the file for writing, but will ensure that any lines we write are appended to the end of the file. Standard 'w' writing mode, by contrast, would cause us to overwrite the file from the first line.

With the file open, we call f.write() with the line to write. We conclude the line with a newline character, \n. You may have heard that line terminators differ between operating systems – Unix-based systems use \n, whereas Microsoft Windows uses \r\n. Fortunately, Python abstracts this detail and we can just use \n regardless of our operating system.

If we want to write more than one line to our file, there are a few ways to go about it. First, if we know exactly what lines to write, we can use a string with multiple \ns, or a multi-line triple-quoted string.

Click to Copy
with open('my_file.txt', 'a') as f: f.write('A new line.\nA second new line.')
Click to Copy
with open('my_file.txt', 'a') as f: f.write("""A new line A second new line.""")

If we want to write lines from a list, we can use f.writelines():

Click to Copy
lines = ['A new line.', 'A second new line.'] with open('my_file.txt', 'a') as f: f.writelines(lines)
  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.