Chapter · File I/O Count Lines 数行 ≈ 15 min · python-file-io python-loops · Open in WolfCode One line of body. The lesson is the choice between sum(1 for _ in f) and the explicit loop. Python · runnable Reset Run # Setup with open("notes.txt", "w") as f: f.write("hello\n\nworld\n \npython\n") def total_lines(path): with open(path) as f: return sum(1 for _ in f) def non_empty_lines(path): with open(path) as f: return sum(1 for line in f if line.strip()) print("total :", total_lines("notes.txt")) print("non-empty:", non_empty_lines("notes.txt")) Loading Python runtime (~5 MB, one-time)… ← Previous Append a Log Next → Homework: Word-Frequency Report