Python Basics: File Handling
Learn to read and write text, CSV, and JSON files – your gateway to data persistence!
1. Text Files
Reading Text Files
Use open()
and read()
to read files. Always close files with close()
or use with
for auto-closing.
Example: Read a story from a file.
# Method 1: Using with (recommended)
with open("story.txt", "r") as file:
content = file.read()
print(content)
# Method 2: Manual close
file = open("story.txt", "r")
print(file.readlines()) # Read as a list of lines
file.close()
Writing to Text Files
"w"
: Overwrite the file.
"a"
: Append to the file.
Example: Save a to-do list.
tasks = ["Homework", "Practice coding", "Read a book"]
with open("todo.txt", "w") as file:
for task in tasks:
file.write(task + "\n") # \n adds a new line
# Append a new task
with open("todo.txt", "a") as file:
file.write("Water the plants 🌱")
2. CSV Files (Comma-Separated Values)
Use the csv
module for spreadsheet-like data.
Reading CSV Files
Example: Read game high scores.
import csv
with open("scores.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(f"Player: {row[0]}, Score: {row[1]}")
Writing CSV Files
Example: Save student grades.
import csv
grades = [
["Alice", "A"],
["Bob", "B"],
["Charlie", "C"]
]
with open("grades.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Grade"]) # Header
writer.writerows(grades)
Pro Tip: Use DictReader/DictWriter for column names:
with open("grades.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["Grade"])
3. JSON Files (Structured Data)
Use the json
module for data like dictionaries.
Reading JSON Files
Example: Load game settings.
import json
with open("settings.json", "r") as file:
settings = json.load(file)
print(f"Volume: {settings['volume']}%")
Writing JSON Files
Example: Save user profiles.
import json
profile = {
"name": "Alex",
"level": 5,
"items": ["sword", "shield"]
}
with open("profile.json", "w") as file:
json.dump(profile, file, indent=4) # indent for readability
Real-World Projects
Project 1: To-Do List Manager (Text Files)
def add_task(task):
with open("todo.txt", "a") as file:
file.write(task + "\n")
add_task("Walk the dog 🐕")
Project 2: Grade Book (CSV)
def add_student(name, grade):
with open("grades.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([name, grade])
add_student("Diana", "A")
Project 3: Game Save System (JSON)
def save_game(level, score):
data = {"level": level, "score": score}
with open("save.json", "w") as file:
json.dump(data, file)
save_game(3, 1500)
Common Mistakes
- ❌ Forgot to close files: Use
with
to avoid this. - ❌ File not found: Double-check file paths.
- ❌ Wrong mode: Using
"w"
instead of"a"
deletes old data.
Key Takeaways
- ✅ Text Files: Use
open()
,read()
,write()
, andwith
. - ✅ CSV Files: Use the
csv
module for rows/columns. - ✅ JSON Files: Use
json.load()
andjson.dump()
for structured data.
Practice Quiz
Which mode appends to a text file?
Answer: "a".
What’s the output of this code?
import json
data = '{"name": "Alice"}'
print(json.loads(data)["name"])
Answer: Alice.
Fun Activity: Build a Story Generator
Create a words.json
file with lists of adjectives, nouns, and verbs.
Read the JSON file and randomly generate silly sentences!
import json
import random
with open("words.json", "r") as file:
words = json.load(file)
adj = random.choice(words["adjectives"])
noun = random.choice(words["nouns"])
verb = random.choice(words["verbs"])
print(f"The {adj} {noun} loves to {verb}!")
Example Output:
The fluffy cloud loves to dance!
What’s Next?
Learn exception handling to gracefully manage file errors (e.g., missing files)!