08. File I/O
Chapter 8 of 36 · 20 min
Reading Files
# Read entire file
with open("prompts.txt", "r") as f:
content = f.read()
print(content)
The with statement ensures the file closes even if errors occur.
Reading Lines
# Read as list of lines
with open("prompts.txt", "r") as f:
lines = f.readlines()
# Or iterate line by line (memory efficient for large files)
with open("prompts.txt", "r") as f:
for line in f:
print(line.strip())
Writing Files
# Write (overwrites existing content)
with open("output.txt", "w") as f:
f.write("Hello, AI\n")
f.write("Second line\n")
# Append (adds to existing content)
with open("output.txt", "a") as f:
f.write("Third line\n")
JSON Files
AI systems frequently use JSON for configuration and data exchange:
import json
config = {
"model": "gpt-4",
"temperature": 0.7,
"batch_size": 32
}
# Write JSON
with open("config.json", "w") as f:
json.dump(config, f, indent=2)
# Read JSON
with open("config.json", "r") as f:
loaded_config = json.load(f)
Handling Missing Files
import json
from pathlib import Path
config_path = Path("config.json")
if config_path.exists():
with open(config_path) as f:
config = json.load(f)
else:
config = {"model": "gpt-4", "temperature": 0.7}
with open(config_path, "w") as f:
json.dump(config, f, indent=2)
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
EXERCISE
- Create a JSON file with three AI model configurations
- Read it back
- Add a fourth model
- Write it back