Lesson 4: File Input & Output

⏱ ~35 min Lesson 4 of 14 💚 Free

Programs that only live in memory disappear when they close. File I/O lets you save data to disk and read it back later — essential for any real application.

Key Concepts

Opening Files

with open('data.txt', 'r') as f:
content = f.read()
Modes: 'r' (read), 'w' (write, creates/overwrites), 'a' (append), 'r+' (read+write). The with block closes the file automatically.

Reading Line by Line

with open('data.txt') as f:
for line in f:
print(line.strip())
strip() removes trailing newline characters. Efficient for large files.

Writing to Files

with open('output.txt', 'w') as f:
f.write('Hello, file!\n')
f.writelines(['line1\n', 'line2\n'])
Each write() call doesn't add a newline — you have to include \n yourself.

JSON Files

import json
with open('data.json', 'w') as f:
json.dump({'name':'Alex','score':92}, f)
with open('data.json') as f:
data = json.load(f)
JSON is the standard format for structured data files.

✅ Check Your Understanding

1. What mode opens a file for writing (creating or overwriting)?

2. What does json.load(f) do?

3. Why use 'with open(...)' instead of just 'open(...)'?