Reading and writing text files
Open, read, write and the with statement.
🎬 Video version coming soon — read it now
Until now, everything your program knew disappeared when it stopped. Files let your program remember: save results, load settings, read data someone else created.
Writing a file
with open("notes.txt", "w") as f:
f.write("Day 1: learned variables\n")
f.write("Day 2: learned loops\n")open(name, mode)opens a file. Mode"w"means write: create the file, or replace it if it exists.\nis a new-line character.write()doesn't add one for you.- In Colab, click the folder icon on the left to see
notes.txtappear.
The with statement
with ... as f: closes the file automatically when the block ends, even if an error happens. Always use it. Unclosed files can lose data.
Reading a file
with open("notes.txt") as f:
content = f.read() # the whole file as one string
print(content)Reading line by line is better for big files:
with open("notes.txt") as f:
for line in f:
print(line.strip()) # strip removes the \n at the endAppending
Mode "a" adds to the end instead of replacing:
with open("notes.txt", "a") as f:
f.write("Day 3: learned files\n")The three modes to remember
"r": read (the default). Error if the file doesn't exist."w": write. Erases existing content first."a": append. Adds to the end.
Opening the wrong file with "w" destroys it, so double-check before running.
Telugu and emoji: use UTF-8
with open("greeting.txt", "w", encoding="utf-8") as f:
f.write("నమస్కారం Vizag 🌊")Adding encoding="utf-8" avoids strange characters and errors with non-English text, especially on Windows.
In one line
Use with open(name, mode) to read ("r"), write ("w") or append ("a") files, and add encoding="utf-8" for Indian languages.
Share with a friend