Skip to content
File Methods

readlines()

Read all remaining lines into a list of strings.

file.readlines(hint=-1)

file.readlines() reads from the current position until EOF and returns a list containing each line as a string element.

Parameters

NameDescription
hintOptional byte threshold; lines will be read until the threshold is exceeded.

Returns

A list of strings representing the lines.

Try it

Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
    f.write('apple\nbanana\ncherry')
    f.seek(0)
    lines = [line.strip() for line in f.readlines()]
    print(lines)

Worth knowing

  • Idiomatic line iteration: Instead of f.readlines(), directly iterating over the file object (for line in f:) is more memory-efficient as it reads on demand.

Related entries