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



