liveBook · Manning

Line

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A line is a sequence of text characters ending at a line boundary or the end of a text stream.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains line-by-line iteration, counting, inspection, and preservation, without descending into text-stream internals.
Examples
Uses wc-style counts, Gashlycrumb letter lookups, and Southern-style transformations of poetry lines.
What it assumes
Assumes basic Python loops and strings while reinforcing file handles, standard input, splitting, and command-line file arguments.
What you can do after
Builds Python programs that read, count, search, index, and transform text one line at a time.
How it connects
Connects lines to files, standard input, for loops, strings, dictionaries, and regular expressions.

Also explained in

Compare how 3 books explain line →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.