Back to results for “Memory Management & Garbage Collection”
Python › File I/O & Context Managers

What is the difference between reading a file with .read(), .readline(), and .readlines()?

Beginner

Answer

read() returns the ENTIRE file's contents as a single string; readline() returns just the NEXT single line (including its trailing newline); readlines() returns a LIST of every line in the file — read() and readlines() both load the whole file into memory at once.
with open("data.txt") as f:
    all_content = f.read()        # one big string

with open("data.txt") as f:
    first_line = f.readline()      # just one line

with open("data.txt") as f:
    lines = f.readlines()          # a list of every line
Real-world example Choosing readline() to process a huge file one line at a time versus read() for a small file you need entirely at once.

Common follow-ups: How does iterating directly over the file object (for line in f) compare to calling readlines()?