-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_file_io.py
More file actions
60 lines (48 loc) · 1.67 KB
/
Copy path05_file_io.py
File metadata and controls
60 lines (48 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Module 05: File I/O
Learn: open(), read/write, context managers (with), pathlib
In the advanced courses, you'll see:
content = safe_path(path).read_text()
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(content)
"""
# --- Writing a file with open() ---
with open("my_file.txt", "w") as f:
f.write("Line 1: Hello from Python!\n")
f.write("Line 2: This is a test file.\n")
print("✅ File written")
# --- Reading a file ---
with open("my_file.txt", "r") as f:
content = f.read()
print(content)
# --- Reading line by line ---
with open("my_file.txt", "r") as f:
lines = f.readlines()
for i, line in enumerate(lines):
print(f" Line {i}: {line.strip()}")
# --- pathlib (the modern way — used in Claude Code agent) ---
from pathlib import Path
# Create a path object
workdir = Path(".")
print(f"Working dir: {workdir.resolve()}")
# Write using pathlib
output_path = Path("sample_output.txt")
output_path.write_text("Written with pathlib! 🎉\n")
print(f"Wrote to: {output_path}")
# Read using pathlib
text = output_path.read_text()
print(f"Read back: {text}")
# Useful path operations
some_path = Path("data/reports/summary.csv")
print(f"Name: {some_path.name}") # summary.csv
print(f"Parent: {some_path.parent}") # data/reports
print(f"Suffix: {some_path.suffix}") # .csv
# mkdir with parents (creates all intermediate dirs)
# Path("output/charts").mkdir(parents=True, exist_ok=True)
# --- Cleanup ---
import os
for f in ["sample_output.txt", "my_file.txt"]:
if os.path.exists(f):
os.remove(f)
print("🧹 Cleaned up temp files")
# 🎯 Exercise: Write a function that reads a file and returns its line count