Reading and writing files
Files let a program keep data after it finishes. Python's built-in open() reads and writes them.
Writing a file
Python
with open("notes.txt", "w") as f:
f.write("Buy milk\n")
f.write("Call Mei\n")
f.write("Finish the Python course\n")
print("Saved.")"w"opens for writing, creating the file or replacing its contents.write()doesn't add line breaks; include\nyourself.withcloses the file automatically (more on that in the next lesson).
Reading a file
Python
with open("notes.txt", "w") as f:
f.write("Buy milk\nCall Mei\nFinish the Python course\n")
with open("notes.txt") as f: # "r" (read) is the default
content = f.read()
print(content)Reading line by line
Looping over a file gives one line at a time, which works even for huge files:
Python
with open("notes.txt", "w") as f:
f.write("Buy milk\nCall Mei\nFinish the Python course\n")
with open("notes.txt") as f:
for number, line in enumerate(f, start=1):
print(number, line.strip()) # strip() removes the trailing \nf.readlines() returns all lines as a list.
File modes
| Mode | Means |
|---|---|
"r" | read (the default); error if the file doesn't exist |
"w" | write; creates the file or overwrites it |
"a" | append; adds to the end |
"x" | create; error if the file already exists |
Python
with open("log.txt", "w") as f:
f.write("Started\n")
with open("log.txt", "a") as f:
f.write("Step 1 done\n")
f.write("Step 2 done\n")
with open("log.txt") as f:
print(f.read())A missing file
Python
try:
with open("does_not_exist.txt") as f:
print(f.read())
except FileNotFoundError:
print("That file doesn't exist yet.")CSV files
The csv module reads and writes comma-separated data, the format spreadsheets export:
Python
import csv
rows = [["name", "score"], ["Asha", 92], ["Leo", 78], ["Mei", 85]]
with open("scores.csv", "w", newline="") as f:
csv.writer(f).writerows(rows)
with open("scores.csv", newline="") as f:
for row in csv.DictReader(f):
print(f"{row['name']} scored {row['score']}")DictReader uses the first line as column names, giving you each row as a dictionary.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.