Working with Files
20 min In ProgressLearning Objectives
- Open, read, and write text files
- Use with statements for safe file handling
- Process CSV data
Reading a File
Use open() with mode 'r' to read. The with statement ensures the file closes automatically.
with open("example.txt", "r") as f:
content = f.read()
print(content)
Writing a File
Use mode 'w' to overwrite or 'a' to append.
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
f.write("Second line\n")
Reading Line by Line
Iterate over a file object to process one line at a time.
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
Course Example: Wage Calculator
Read a CSV, process wages, and write results to a new file.
import csv
# Simulated in-memory processing
import io
input_csv = "name,hours\nAlice,8\nBob,10"
output_data = []
reader = csv.reader(io.StringIO(input_csv))
next(reader) # skip header
for row in reader:
row[1] = int(row[1]) * 15
output_data.append(row)
print(output_data)
📝 Exercise: Write a Poem
Write a list of lines to a file called poem.txt, then read it back and print it.
code.py
Output