Skip to content
File Methods

readline()

Read and return one line from the file.

file.readline(size=-1)

file.readline() reads characters from the current position up to and including the next newline (\n).

Returns an empty string ('') when reaching End-Of-File (EOF).

Parameters

NameDescription
sizeOptional maximum number of characters to read from the line.

Returns

A string containing the single line (including trailing newline, if present).

Try it

Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
    f.write('Line 1\nLine 2\nLine 3')
    f.seek(0)
    print(f.readline().strip())
    print(f.readline().strip())

Worth knowing

  • Trailing newlines: The returned string includes the trailing \n character, except on the last line if it lacks one. Use .rstrip('\n') to clean it.

Related entries