Computer Science · Ch 2 — File Handling in Python
The readline([n]) method
The readline([n]) method
The readline() method reads exactly one line from a file. A "line" in a text file is any sequence of characters that ends with a newline character (\n). This is important: the newline is part of the line, not a separator between lines. When you call readline(), it reads from the current file position until it hits a \n, and it includes that \n in the string it returns.
You can also pass an optional argument n to readline([n]). This argument specifies the maximum number of bytes (characters, for a text file) to read. However, there is a catch: even if you specify a large n, the method will never read past the next newline character. It reads at most n bytes, but stops early if it reaches \n first. If you pass no argument, or a negative number, the method reads the entire next line (including the newline) and returns it as a string.
The newline character \n is always included in the returned string, unless you are reading the very last line of a file that does not end with a newline.
Example from the textbook:
Suppose myfile.txt contains the line Hello everyone followed by a newline.
myobject = open("myfile.txt", 'r')
myobject.readline(10) # reads first 10 characters of the first line
This returns 'Hello ever' — the first 10 characters of Hello everyone\n.
If you then call myobject.readline() with no argument, it reads the rest of that same line (since the file pointer is now at position 10), returning 'yone\n'.
Reading a complete line (no argument or negative argument):
myobject = open("myfile.txt", 'r')
print(myobject.readline())
This prints 'Hello everyone\n' — the entire first line including the newline.
Reading the entire file line by line:
To read all lines from a file using readline(), you use a loop. The method returns an empty string '' when it reaches the end of the file (EOF). So the standard pattern is:
myobject = open("myfile.txt", 'r')
line = myobject.readline()
while line != '':
print(line, end='') # end='' avoids adding an extra newline
line = myobject.readline()
myobject.close()
This process of repeatedly calling readline() in a loop is called looping over a file object or iterating over a file object. It is a fundamental technique for processing files line by line without loading the entire file into memory at once. …