Python File Handling (Write Files)
Variables disappear when a program ends. To keep data, a program writes it to a file: a list of scores, a log of events, a report to send to someone. Python opens files with the built-in open function. In our editor, files your program creates appear in the file list on the left, where you can open or download them.
Opening a file for writing
open(name, mode) returns a file object. The mode says what you want to do: "w" writes a new file (and empties it if it already exists), "a" appends to the end, "x" creates a file but fails if it exists, and "r", the default, reads. Always open files with a with statement: it closes the file automatically when the block ends, even if an error happens:
with open("notes.txt", "w") as f:
f.write("Shopping list\n")
f.write("- rice\n")
f.write("- milk\n")
with open("notes.txt", "a") as f:
f.write("- apples\n")
print(open("notes.txt").read(), end="")Shopping list - rice - milk - apples
write does not add a new line: put \n at the end of each line yourself. It accepts only strings, so convert numbers with str or an f-string first.
Writing many lines
writelines writes a list of strings, and print can write to a file with its file argument, adding the new line for you:
scores = {"Asha": 91, "Ravi": 78, "Meera": 85}
with open("scores.txt", "w", encoding="utf-8") as f:
for name, score in scores.items():
print(f"{name},{score}", file=f)
with open("scores.txt") as f:
print(f.read(), end="")Asha,91 Ravi,78 Meera,85
encoding="utf-8" makes sure that letters such as é, ₹ and Hindi characters are saved correctly on every computer. It is a good habit for every text file.
Files and folders
The os and pathlib modules check, list and delete files:
import os
from pathlib import Path
Path("data").mkdir(exist_ok=True)
Path("data/report.txt").write_text("all good\n")
print(os.path.exists("data/report.txt"))
print(sorted(os.listdir("data")))
print(Path("data/report.txt").read_text(), end="")
os.remove("data/report.txt")
print(os.path.exists("data/report.txt"))True ['report.txt'] all good False
Path objects represent file paths. write_text and read_text write or read a whole file in one call, which is handy for small files.
Be careful with "w"
Opening an existing file with "w" erases its contents at once, before you write anything. When you only want to add data, use "a"; when the file must not be overwritten, use "x" or check with os.path.exists first.
Practice exercises
- Write the numbers 1 to 10 to a file, one per line, and print the file.
- Ask the user for three things to do and append each one to
todo.txt. - Save a dictionary of names and phone numbers as lines of the form
name: number. - Create a folder with
Path.mkdirand write two files into it, then list the folder.