Level: Intermediate | Prerequisite: Week 5 (Exception Handling)
Learning Goals
- Handle text files safely with
with open - Read and write CSV files using the
csvmodule - Save and load structured data in JSON
1. Text Files
with Statement (Recommended)
Automatically closes the file.
#Write
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line")
f.writelines(["A\n", "B\n", "C\n"])
#Read
with open("notes.txt", encoding="utf-8") as f:
content = f.read() #All at once
#Or
for line in f: #One line at a time
print(line.rstrip())
Modes
| Mode | Meaning |
|---|---|
r |
Read (default) |
w |
Write (overwrite existing content) |
a |
Append |
r+ |
Read/Write |
b |
Binary (e.g., rb, wb) |
⚠️ Always specify encoding="utf-8" (safe for Korean).
2. CSV
Comma-separated table format.
import csv
#Write
with open("scores.csv", "w", encoding="utf-8", newline="") as f:
w = csv.writer(f)
w.writerow(["name", "score"])
w.writerows([["Alice", 92], ["Bob", 78]])
#Read
with open("scores.csv", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], row["score"])
⚠️ Missing newline="" causes blank lines (Windows).
3. JSON
Serialize structured data to text.
import json
data = {
"name": "Hong Gil-dong",
"skills": ["Python", "SQL"],
"active": True,
}
#Save
with open("profile.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
#Load
with open("profile.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["skills"])
Options:
ensure_ascii=False— Keep Korean characters as isindent=2— Indent for human readability
Key Examples (examples/)
| File | Content |
|---|---|
01_text.py |
Text File Read/Write |
02_csv_write.py |
Write CSV |
03_csv_read.py |
Read CSV (DictReader) |
04_json.py |
JSON dump/load |
⚠️ Common Mistakes
- Omitting
closeafteropen— Automatically handled by usingwith. encodingmissing — Korean characters break on Windows.json.dumpvsjson.dumps—dumpis for files,dumpsis for strings.- CSV
newline=""missing — Empty lines are added on Windows. - Types that cannot be saved as JSON —
datetime, user-defined classes. Conversion is needed.
❓ FAQ
Q1. Which should you use, CSV or JSON? A. Tabular data uses CSV, nested/structured data uses JSON.
Q2. Can I read large files all at once? A. They are loaded into memory, so GB-sized files are risky. Iterate line by line or use generators.
Q3. What is pickle?
A. Stores the Python object as it is. However, it cannot be read in other languages and poses a security risk. JSON is recommended.
📝 Exercises (exercises/)
exercise1.md— Notepad (text addition)exercise2.md— CSV score statisticsexercise3.md— Permanent To-Do JSON storage
Next Week
Week 7. Object-Oriented (1)