The readline()
function is a method in Python used to read a single line from a file. When called, it reads the next line from the file object that it is applied to, starting from the current position. If no other argument is provided, it reads until the newline character or the end of the file.
Parameter Values
Parameter | Description |
---|---|
size | Specifies the number of characters to read from the file. If not specified, it will read the entire line. |
Return Values
The readline()
method returns a line from the file as a string
.
How to Use readline()
in Python
Example 1:
The readline()
method reads a single line from the file, starting at the current file cursor position.
with open('file.txt', 'r') as file:
line = file.readline()
print(line)
Example 2:
It is possible to read multiple lines using readline()
in a loop until it reaches the end of the file (EOF).
with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()