Module 2: Lists, dictionaries and files · 10 min
Reading and writing files
Use with open(...) so the file is closed automatically, even if an error happens.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\nsecond line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
Mode "w" writes (and erases an existing file!), "a" adds to the end, and "r" (the default) reads.
Errors are normal. try and except let your program react instead of crashing:
try:
with open("missing.txt") as f:
text = f.read()
except FileNotFoundError:
print("That file does not exist")