Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 149 · Files and Errors

Reading and Writing Files

Learn to read and write text files in Python with open() and the with statement. Covers file modes, reading line by line, appending, and encodings.

Most useful programs outlive a single run. A to-do app remembers your tasks, a game keeps high scores, and a script that cleans up data needs somewhere to put the result. The simplest place to keep information between runs is a file.

In this lesson you'll open files with the built-in open() function, write text into them, read it back in several ways, and learn why the with statement is the right way to do all of it. You'll also meet file modes and encodings, the two details that cause most file-related surprises.

About the editors on this page: the browser runner gives every run its own small in-memory file system. Files you create exist until the run finishes, then disappear. That's why each example below writes a file first and then reads it back in the same run. On your own computer, the files stay on disk.

Opening, writing and reading a file

Working with a file always follows the same three steps: open it, use it, close it. open() takes a file name and a mode: a short string that says what you plan to do. "w" means write, "r" means read.

Python Write a file, then read it back

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step by step:

  • open("greeting.txt", "w", ...) creates the file (or empties it if it already exists) and returns a file object.
  • with ... as file: gives that object a name and guarantees the file is closed when the indented block ends, even if an error happens inside it.
  • file.write() adds text. Unlike print(), it doesn't add a line break for you, so you write \n yourself.
  • file.read() returns the whole contents as one string.

Notice that text is still available after the second with block. The file is closed, but the string you read from it lives on like any other variable.

Why with matters

You can call open() without with, but then you have to remember to call close() yourself:

Python
file = open("notes.txt", "w", encoding="utf-8")
file.write("Remember to close me.")
file.close()

If an exception is raised between open() and close(), the close() line never runs. An unclosed file can hold on to system resources, and data you wrote may still be sitting in a memory buffer instead of on disk. The with statement closes the file no matter how the block exits, so it's the standard way to work with files. You'll see how it works under the hood in Context Managers.

Tip: you can open two files in one with statement: with open("in.txt") as source, open("out.txt", "w") as target:. Both are closed at the end.

File modes

The mode string tells Python what kind of access you want. These are the ones you'll use most:

Mode Meaning If the file doesn't exist If it does exist
"r" Read (the default) FileNotFoundError Reads from the start
"w" Write Creates it Empties it first
"a" Append Creates it Adds to the end
"x" Exclusive create Creates it FileExistsError
"r+" Read and write FileNotFoundError Keeps the contents

Add b for binary mode ("rb", "wb") when the file isn't text, such as an image or a ZIP archive. In binary mode you read and write bytes objects instead of strings, and no encoding is involved.

The most important line in that table is the warning on "w": opening an existing file for writing wipes it out immediately, before you write anything. If you want to keep what's there and add more, use "a":

Python Write versus append

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The third open() call has no mode at all, so it uses the default, "r".

Reading line by line

read() is fine for small files, but it loads everything into memory at once. For larger files, or whenever you want to handle one line at a time, loop over the file object directly. Each pass of the loop gives you the next line, including its trailing \n:

Python Looping over lines

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two common patterns appear here:

  • Looping with for line in file reads lazily, so it works even for files bigger than your computer's memory. line.rstrip() removes the line break (and any trailing spaces) before printing.
  • file.read().splitlines() gives you a list of lines without the \n characters. It's handy when the file is small and you want a list right away.

There are also two methods you'll see in other people's code. file.readline() reads a single line and returns an empty string "" at the end of the file. file.readlines() returns a list of all lines, each still ending in \n.

Writing many lines

write() takes one string. To write several, either call it in a loop, join them yourself, or use writelines(), which takes any iterable of strings. Like write(), it never adds line breaks for you.

You can also send print() output to a file with its file argument. That's convenient because print() adds the newline and converts numbers to text:

Python print() into a file

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The format specs :<6 and :>3 line the columns up; String Formatting covers them in detail.

Encodings

A text file is really a sequence of bytes on disk. An encoding is the rule that turns characters into bytes and back again. UTF-8 can represent every character in Unicode (accented letters, Chinese, Arabic, emoji) and is the standard almost everywhere today.

If you leave out encoding=, Python uses a platform default. On macOS and Linux that's UTF-8, but on Windows it has historically been an older code page, so a file written on one machine can come out garbled on another. Python is moving toward UTF-8 everywhere, but the safest habit is simple: always pass encoding="utf-8" when opening text files.

Python Characters and bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Plain ASCII letters take one byte each in UTF-8, while é takes two, each Japanese character three, and the snake emoji four. Reading the same bytes with the wrong encoding is what produces strings like café. If you read a file and Python raises UnicodeDecodeError, the file was probably saved with a different encoding than the one you asked for.

When files go wrong

Opening a file that doesn't exist in read mode raises FileNotFoundError. That's an exception you'll often want to handle:

Python
try:
    with open("settings.txt", encoding="utf-8") as file:
        settings = file.read()
except FileNotFoundError:
    settings = ""

You'll learn all about try and except in Exceptions and try/except. For working with folders, file names and checking whether a path exists, the pathlib module offers a modern, object-based approach, including shortcuts like Path("notes.txt").read_text(encoding="utf-8").

Watch out: file names are relative to the program's current working directory, which isn't always the folder your script lives in. If a file "isn't there" but you can see it in your file manager, print Path.cwd() to check where Python is looking.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What happens when you open an existing file with mode "w"?

    Mode "w" truncates the file immediately. Use "a" to add to the end, or "x" to refuse to touch an existing file.
  2. 2. Why is with open(...) as f: preferred over calling open() and close() yourself?

    The with statement guarantees the file is closed when the block ends, whether it finishes normally or because of an exception.
  3. 3. When you loop with for line in file:, what does each line contain?

    Each line keeps its trailing "\n". Use line.rstrip() or read().splitlines() to drop it.
  4. 4. Which argument makes a text file behave the same on Windows, macOS and Linux?

    Without an explicit encoding, Python falls back to a platform default that differs between systems. Passing encoding="utf-8" removes the guesswork.
  5. 5. What does file.write("done") do differently from print("done", file=file)?

    write() outputs exactly the string you give it. print() adds its end character, which is a newline by default.

Summary

  • open(name, mode, encoding="utf-8") returns a file object; use it inside a with block so it always gets closed.
  • Modes: "r" read (default), "w" write (empties the file), "a" append, "x" create only; add b for binary data.
  • read() gives the whole file, for line in file reads lazily one line at a time, and read().splitlines() gives a list without newlines.
  • write() and writelines() never add line breaks; print(..., file=f) does.
  • Always pass encoding="utf-8" for text files, and expect FileNotFoundError when reading a file that may not exist.

Next: CSV Files, where you'll read and write spreadsheet-style data with the csv module.