Sometimes you need your program to save data so it's still there next time you run it. That's where file handling comes in!
Syntax:
file = open("filename.txt", "w")
file.write("content")
file.close()
Better β using with (auto-closes):
with open("scores.txt", "w") as file:
file.write("Alice: 85\n")
file.write("Bob: 92\n")
file.write("Charlie: 78\n")
# File automatically closed β
"w" = write (overwrites), "a" = append (adds to end), "r" = read.
Read entire file:
with open("scores.txt", "r") as file:
content = file.read()
print(content)
Read line by line:
with open("scores.txt", "r") as file:
for line in file:
print(f"Line: {line.strip()}")
with open("scores.txt", "a") as file:
file.write("Diana: 95\n")
# Save scores to file
def save_scores(scores, filename):
with open(filename, "w") as f:
for score in scores:
f.write(str(score) + "\n")
print(f"Saved {len(scores)} scores β
")
# Load scores from file
def load_scores(filename):
scores = []
with open(filename, "r") as f:
for line in f:
scores.append(int(line.strip()))
return scores
# Test it
scores = [85, 92, 78, 90, 88]
save_scores(scores, "my_scores.txt")
loaded = load_scores("my_scores.txt")
print(f"Loaded: {loaded}")
print(f"Average: {sum(loaded)/len(loaded):.1f}")
FileNotFoundError if the file doesn't exist.