Chapter 7

File Handling

FREE Reading from and Writing to Files
Article Β· 15 min
πŸ“ Homework 13

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!


πŸ“ Why Use Files?

  • Data persists β€” doesn't disappear when the program ends
  • You can share data between programs
  • You can process large amounts of data at once

✍️ Writing to a File

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 βœ…
πŸ”‘ File Modes: "w" = write (overwrites), "a" = append (adds to end), "r" = read.
1
Practice 1
✏️ Try it yourself!
1 Code
Write a program that saves "Hello, World!" to a file called "greeting.txt".
2 Code
Write a program that saves 3 lines of text to "notes.txt".

πŸ“– Reading from a File

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()}")
2
Practice 2
✏️ Try it yourself!
1 Code
Read "greeting.txt" and print its contents.
2 Code
Read "notes.txt" and count how many lines it has.

βž• Appending to a File

with open("scores.txt", "a") as file:
    file.write("Diana: 95\n")
3
Practice 3
✏️ Try it yourself!
1 Code
Create a log system that appends a new entry each time the program runs.

🎯 Exam-Style Example: Score Tracker

# 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}")
4
Practice 4
✏️ Try it yourself!
1 Code
Modify the score tracker to handle the FileNotFoundError if the file doesn't exist.
2 Code
Write a program that reads a file and copies only the even numbers to "evens.txt".
3 Code
Write a "to-do list" program that can add, view, and save tasks to "tasks.txt".