Lesson 43/48 ยท ๐ Working with the Real World
๐ Working with the Real WorldLesson 43/48
Phase 8 ยท Working with the Real World22 min
Reading and Writing Files
open(), read(), write(), and the with statement
How would you approach this? Think first, then expand.
Files are how programs communicate with the outside world. Config files, log files, CSV reports, JSON data, everything important lives in files.
Reading a filepython
# Always use 'with', it auto-closes the file
with open("data.txt", "r") as f:
content = f.read() # Read entire file as string
print(content)
# Read line by line (better for large files)
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes the \nWriting a filepython
# "w" overwrites, "a" appends
with open("output.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
# Write multiple lines at once
lines = ["Alice,30\n", "Bob,25\n", "Carol,35\n"]
with open("people.csv", "w") as f:
f.writelines(lines)Working with CSV filespython
import csv
# Read CSV
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
# Write CSV
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
with open("out.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(people)Always use the `with` statement. Without it, if your code crashes, the file stays open and locked. The
with statement guarantees the file is closed even if an exception occurs.๐In the Real World...
Pipeline scripts read config files, write deployment logs, process CSV reports. Kubernetes operators read YAML, write status files. Every real automation script touches the filesystem.
Practice Exercises
0/4 solvedExercise 1 of 4easy
โฑ 00:00Count Lines in a Log
Given the log content below as a multi-line string, split it into lines and count them.
Expected output:
Expected output:
Log has 4 linessolution.py
1 / 4
Exercise 2 of 4easy
โฑ 00:00Parse a CSV String
Parse the CSV data and print each person's name and age.
Expected output:
Expected output:
Alice is 30 years oldBob is 25 years oldCarol is 35 years oldsolution.py
2 / 4
Exercise 3 of 4easy
โฑ 00:00Count Errors in Log
Count how many ERROR lines are in the log.
Expected output:
Expected output:
ERROR count: 2solution.py
3 / 4
Exercise 4 of 4medium
โฑ 00:00Extract Error Messages
From the log, extract only the message part of ERROR lines (after "ERROR: ").
Expected output:
Expected output:
Disk fullMemory limit exceededsolution.py
4 / 4
Solve all 4 exercises to unlock completion