liveBook · Manning

Readline

As explained in The Quick Python Book, Fourth Edition

readline is a file-object method that reads and returns one line, including its terminating newline when present, or an empty string at end of file.

readline is a file-object method that reads and returns one line at a time. It includes the terminating newline when present and returns an empty string when no data remains. section 13.1 section 13.4

Use readline with these rules in mind:

  • Call it repeatedly to advance through a file: the first call returns the first line, the next returns the second, and so on. section 13.1
  • Test for "" to detect end of file; this also makes a loop suitable for counting lines. section 13.4
  • Prefer iteration over the file object for simpler, one-line-at-a-time processing, especially with large files. section 13.4
  • Remember that a very long line without a newline can still require substantial memory; an optional argument can limit data read. section 13.4

Read and count lines

with open("myfile", "r") as file_object: line = file_object.readline() file_object = open("myfile", "r") count = 0 while file_object.readline() != "": count += 1 print(count) file_object.close() The first example reads one line. The second continues until readline returns an empty string. section 13.1 section 13.4

with open('myfile', 'r') as file_object:
   line = file_object.readline() 

Shows the compact preferred pattern for opening a file and calling readline. section 13.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines returned line contents, successive reads, end-of-file behavior, memory caveats, and optional limits without detailing the reference signature.
Examples
Uses a with-open call, a repeated-read line counter, and sys.stdin.readline for terminal input.
What it assumes
Assumes familiarity with opening files and file objects while demonstrating those objects’ role before reading begins.
What you can do after
Apply it via Python file objects to read lines, detect end of file, and process input incrementally.
How it connects
Connects file objects with context managers, file iteration, readlines, newline handling, and standard input.

Also explained in

Compare how 4 books explain readline →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.