Reading & Writing Files
Variables disappear when a program ends, but files last. Reading and writing files lets your programs save notes, scores, settings and records, then load them again next time.
Opening a file
The built-in open() function connects your program to a file. You give it the file name, a mode that says what you want to do, and (for text) an encoding.
| Mode | Meaning | If the file doesn't exist |
|---|---|---|
"r" | Read (the default) | Raises FileNotFoundError |
"w" | Write, erasing any existing content | Creates it |
"a" | Append: add to the end | Creates it |
"x" | Create a new file only | Creates it (raises FileExistsError if it exists) |
"r+" | Read and write an existing file | Raises FileNotFoundError |
"b" (added, e.g. "rb") | Binary mode for images, PDFs and other non-text files | Depends on the other letter |
Always open files with a with block. It closes the file automatically when the block ends, even if an error happens inside it. (You'll learn how this works in Context Managers.)
"w" destroys the existing content.Writing to a file
items = ["Unga", "Sukuma wiki", "Milk"]
with open("shopping.txt", "w", encoding="utf-8") as file:
for item in items:
file.write(item + "\n")
print("Saved", len(items), "items")
The file shopping.txt now contains:
Unga Sukuma wiki Milk
Unlike print(), write() does not add a newline for you, so we add "\n" ourselves. It also only accepts strings: to save a number, convert it first with str() or an f-string.
Mode "w" wipes the file the moment it opens, before you write anything. Opening your only copy of important data in "w" mode by accident deletes it. Use "a" to add to a file, or "x" if you want Python to refuse to overwrite an existing file.
Reading a file
Read everything at once
with open("shopping.txt", "r", encoding="utf-8") as file:
content = file.read()
print(repr(content))
print(len(content), "characters")
read() returns the whole file as one string. Using repr() shows the hidden newline characters at the end of each line.
Read line by line
Looping over a file object gives you one line at a time. This is the best approach for large files because only one line is in memory at once. Use strip() to remove the newline at the end of each line.
with open("shopping.txt", encoding="utf-8") as file:
for number, line in enumerate(file, start=1):
print(number, line.strip())
readline() and readlines()
with open("shopping.txt", encoding="utf-8") as file:
first = file.readline() # just the next line
rest = file.readlines() # all remaining lines, as a list
print(repr(first))
print(rest)
A file remembers its position. After readline() has read the first line, readlines() continues from the second.
Appending to a file
with open("shopping.txt", "a", encoding="utf-8") as file:
file.write("Bread\n")
file.writelines(["Eggs\n", "Tea leaves\n"])
with open("shopping.txt", encoding="utf-8") as file:
print(file.read().splitlines())
writelines() writes each string in a list one after another. Like write(), it doesn't add newlines. splitlines() splits text into lines and removes the newline characters, which is a neat alternative to calling strip() on every line.
Handling missing files
Reading a file that doesn't exist raises FileNotFoundError. Catch it to give the user a friendly message instead of a crash (more on this in Try, Except & Finally).
try:
with open("diary.txt", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("diary.txt does not exist yet.")
The pathlib shortcut
For small files, pathlib.Path can read or write a whole file in one line, and it can check whether a file exists.
from pathlib import Path
notes = Path("notes.txt")
notes.write_text("Revise loops\nPractise files\n", encoding="utf-8")
print(notes.exists())
print(notes.read_text(encoding="utf-8").splitlines())
A practical example: counting lines and words
text = """Python makes files easy.
Files store data between runs.
Easy, right?"""
with open("essay.txt", "w", encoding="utf-8") as file:
file.write(text)
with open("essay.txt", encoding="utf-8") as file:
lines = file.readlines()
words = sum(len(line.split()) for line in lines)
print("Lines:", len(lines))
print("Words:", words)
Always pass encoding="utf-8" for text files. Without it, Python uses your system's default encoding, which on Windows may not be UTF-8. Then names such as "Zoë" or symbols such as "°C" can appear garbled or cause a UnicodeDecodeError on another computer.
A relative file name like "shopping.txt" is looked up in the current working folder of the terminal, not necessarily the folder containing your script. If you get FileNotFoundError for a file you can see, check which folder your terminal is in, or build the path from the script's location with Path(__file__).parent / "shopping.txt".
Key points
- Use
with open(name, mode, encoding="utf-8") as file:so files close automatically. "r"reads,"w"overwrites,"a"appends and"x"creates new files only.write()doesn't add newlines; add"\n"yourself.- Loop over the file for big files; use
read()orsplitlines()for small ones. - For structured data, use the CSV and JSON modules.
Tip: use the ← and → keys to move between pages.
