Write one or more lines to a file in Python

David Y.

The Problem

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:

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:

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.

with open('my_file.txt', 'a') as f: f.write('A new line.\nA second new line.')
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():

lines = ['A new line.', 'A second new line.'] with open('my_file.txt', 'a') as f: f.writelines(lines)

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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