Why files?
Variables disappear when your program ends. To keep data – notes, scores, settings – save it in a file.
Writing a file
with open("notes.txt", "w") as file:
file.write("Buy milk\n")
file.write("Call Asha\n")
print("Saved!")Output
Saved!
open("notes.txt", "w")opens the file for writing. If it doesn't exist it's created; if it does, it's emptied first.withautomatically closes the file when the block ends – even if there's an error.write()doesn't add a new line for you, so we add\nourselves.
Reading a file
with open("notes.txt", "w") as file:
file.write("Buy milk\nCall Asha\n")
with open("notes.txt") as file:
content = file.read()
print(content)Output
Buy milk Call Asha
Or go through it line by line – strip() removes the new-line character at the end of each line:
with open("notes.txt", "w") as file:
file.write("Buy milk\nCall Asha\n")
with open("notes.txt") as file:
for number, line in enumerate(file, start=1):
print(number, line.strip())Output
1 Buy milk 2 Call Asha
Adding to a file
Mode "a" (append) adds to the end instead of wiping the file:
with open("log.txt", "w") as file:
file.write("Day 1: started Python\n")
with open("log.txt", "a") as file:
file.write("Day 2: learned loops\n")
with open("log.txt") as file:
print(file.read())Output
Day 1: started Python Day 2: learned loops
| Mode | Meaning |
|---|---|
"r" | read (the default) |
"w" | write – creates or empties the file |
"a" | append – add to the end |
When the file is missing
try:
with open("missing.txt") as file:
print(file.read())
except FileNotFoundError:
print("That file doesn't exist yet.")Output
That file doesn't exist yet.
Remember: Always use
with open(...). It closes the file for you, so your data is saved properly.