// python · beginner
Reading and Writing Files in Python
Learn how to save and load text files in Python using open() and with, the difference between read, write and append modes, and how to handle missing files.
Everything your program stores in variables disappears the moment it finishes. To remember things between runs, such as a high score, a to-do list or a settings file, you need to save them to a file. Python makes this pleasantly simple.
Writing your first file
with open("notes.txt", "w") as file:
file.write("Learning Python with CodeRunner\n")
file.write("Files are easier than I thought!\n")
Run it, and a file called notes.txt appears in the same folder as your script. Here’s what each part means:
open("notes.txt", "w")opens the file in write mode, creating it if it doesn’t exist.with ... as file:gives the open file a name,file, and automatically closes it when the indented block ends, even if an error happens..write()adds text. It doesn’t add a new line for you, so include\nyourself.
Careful:
"w"mode wipes the file before writing. Ifnotes.txtalready had something in it, that’s gone.
The three modes you need
| Mode | Name | What it does |
|---|---|---|
"r" |
read | opens an existing file to read it (this is the default) |
"w" |
write | creates the file, or empties an existing one, then writes |
"a" |
append | adds to the end of the file, creating it if needed |
To add to a file without losing what’s there, use "a":
with open("notes.txt", "a") as file:
file.write("Append mode keeps the old lines.\n")
Reading a file
There are three common ways to read, depending on what you need.
All at once, as a single string:
with open("notes.txt") as file:
content = file.read()
print(content)
Line by line, which is the best choice for big files because it doesn’t load everything into memory:
with open("notes.txt") as file:
for line in file:
print(line.strip())
Each line includes the newline character at the end, so .strip() removes it. Without it, print would add a second line break and you’d see blank lines between each one.
As a list of lines:
with open("notes.txt") as file:
lines = file.read().splitlines()
print(lines)
.splitlines() gives you a tidy list without the \n characters.
Writing a list to a file
Files store text, so numbers must be converted with str() (or an f-string) before writing:
scores = [72, 85, 90]
with open("scores.txt", "w") as file:
for score in scores:
file.write(f"{score}\n")
And converted back with int() when reading:
scores = []
with open("scores.txt") as file:
for line in file:
scores.append(int(line))
print(sum(scores)) # 247
int() ignores the newline at the end of each line, so no .strip() is needed here.
When the file doesn’t exist
Reading a file that isn’t there raises a FileNotFoundError. That’s normal the very first time a program runs, so handle it with try and except:
try:
with open("highscore.txt") as file:
high_score = int(file.read())
except FileNotFoundError:
high_score = 0
print(f"High score: {high_score}")
You can also check first with the pathlib module:
from pathlib import Path
if Path("highscore.txt").exists():
print("Found a saved high score")
Where does the file go?
A file name on its own, like "notes.txt", is relative to the folder your terminal is in when you run the script, which isn’t always the folder the script is saved in. If your file seems to vanish, check where you ran the program from. The first program guide explains cd if you need a refresher.
Special characters and encoding
If your text includes characters such as é, £ or emoji, specify the encoding so it works the same on every computer:
with open("menu.txt", "w", encoding="utf-8") as file:
file.write("Café crème: £3.20 ☕\n")
Use the same encoding="utf-8" when reading it back. It’s a good habit to include it always.
Mini project: a high-score keeper
import random
def load_high_score():
try:
with open("highscore.txt", encoding="utf-8") as file:
return int(file.read())
except (FileNotFoundError, ValueError):
return 0
def save_high_score(score):
with open("highscore.txt", "w", encoding="utf-8") as file:
file.write(str(score))
high = load_high_score()
score = random.randint(1, 100)
print(f"You scored {score}! (High score: {high})")
if score > high:
print("New high score!")
save_high_score(score)
Run it several times. The high score survives between runs because it’s saved in a file. It also handles a missing file and a file containing rubbish (ValueError). Challenge: save the player’s name alongside their score, on the same line, separated by a comma.
Key points
with open(name, mode) as file:opens a file and closes it automatically."r"reads,"w"overwrites,"a"appends.- Files hold text: convert numbers with
str()to write andint()to read. - Loop over a file to read it line by line, using
.strip()to remove newlines. - Catch
FileNotFoundErrorfor files that may not exist yet.
Next, work with spreadsheet data in Working with CSV Files in Python.