A line is a sequence of text read up to a line boundary or the end of a text stream. Python file iteration supplies one line at a time, making lines a practical unit for counting, searching, and transforming text. section 6.1.2 section 15.0
Common line-processing patterns include:
- Iterate over each open file handle, then iterate over each line in that file. section 6.1.2
- Increment a line counter once per iteration; the loop ends when the file reaches its end. section 6.1.3 section 6.3.2
- Inspect or transform each line while retaining its line breaks when output structure matters. section 7.0 section 15.0
Count lines with a file loop
Set a counter to zero, then add one for every line: `num_lines = 0` followed by `for line in fh: num_lines += 1`. The same loop can add `len(line)` for characters and `len(line.split())` for approximate word counts. section 6.1.3 section 6.3.2
Search and transform complete lines
A lookup program reads a letter from the beginning of each line and stores the line for later retrieval. A text transformer reads input line by line so its output keeps the original line breaks. section 7.0 section 15.0
for fh in args.file: # ONE LOOP!
for line in fh: # TWO LOOPS!
# process the line
Use the nested-loop listing to see the minimal structure for processing every line in every input file. section 6.1.2


