Thuta Learning
Python
IntermediateProgrammingBeginner

Python Read Files

PythonLesson 3125 min

What you'll walk away with

  • Predict what type read(), readline() and readlines() return, and whether the \n is included
  • Stream a file with a for loop to read huge files with little memory
  • Explain why a second read() returns "" because of the file position
  • Read CSV files with the csv module instead of split(",")

Explain it simply

Explain it simply

Reading a file is like watching a film. The player keeps a marker of where you are (the position). read() watches straight through to the end, readline() watches a single scene, and a for loop watches scene after scene.

Once you reach the end there is nothing left to watch, so calling read() again gives an empty string "". For big files, watching one scene at a time is best, because you never have to hold the whole film in your head at once.

Problem → Why → Solution

The problem: a big log file eats all the memory

A developer writes this script to count ERROR lines. It works on a 100 KB test file. Run against the 6 GB log on the production server, the process swallows all available memory and dies. And when they call read() a second time to print the first ERROR line, nothing comes out.

count_errors.py
with open("app.log", encoding="utf-8") as f:
    text = f.read()                     # the whole 6 GB file as one string
    errors = text.split("\n")           # ...and a second copy as a list
    print(sum("ERROR" in line for line in errors))

    again = f.read()                    # returns "" - the position is at the end
    print(again[:80])

Why does this happen?

read() loads the entire file into memory as one string, and split() makes a second full copy as a list. Memory grows in step with the file size. The second read() returns "" because a file object has a position: the first read() already moved it to the end, so there is nothing left to read.

Core concept: four ways to read, one position

A file object opened in text mode offers four ways to read. All of them start at the current position and move it forward by however much they read. Which one you pick depends on the file's size and on what you need to do with the data.

MethodReturnsUse it when
f.read()All remaining content as one strThe file is small and needed whole
f.readline()One line with its \n, or "" at the endYou need just a header line
f.readlines()A list of lines, each with \nYou need a list and the file is small
for line in f:One line per loop stepLarge files and most everyday work

for line in f: keeps only one line (plus a small buffer) in memory, so memory use is about the same whether the file is 6 GB or 6 KB. Every line arrives with its \n at the end, except possibly the very last line if the file does not end with a newline. So strip it with line.rstrip("\n") or line.strip() before comparing or printing.

An empty string is how you detect the end. If readline() returns "", the file is finished; if it returns "\n", that is just a blank line and there is more to read. To read from the beginning again, move the position back with f.seek(0) or open the file afresh. For large binary files, pass a size such as f.read(65536) and read chunk by chunk until you get an empty result back.

Reading in text mode also decodes bytes into characters, and that step can fail. If a single byte is not valid UTF-8, the read raises UnicodeDecodeError at that point even when the rest of the file is fine. When you only need the readable parts, for example while searching old logs, open the file with errors="replace" and each undecodable byte becomes the U+FFFD replacement character instead of stopping the program. Avoid it for data you must store accurately, because it silently changes the content.

Mental model: a cursor that only moves forward
  1. open() puts the cursor at the start
  2. Each read moves the cursor forward
  3. At the end, reads return ""
  4. seek(0) jumps back to the start

The read methods differ only in how far they move the cursor per call.

General pattern

python
with open(path, encoding="utf-8") as f:
    for line in f:                  # streams: one line in memory at a time
        process(line.rstrip("\n"))

with open(path, encoding="utf-8") as f:
    header = f.readline()           # just the first line
    rest = f.read()                 # everything after it

text = path.read_text(encoding="utf-8")   # small files only

The everyday choice is for line in f:, stripping the \n from each line. Calling readline() and then read() continues from wherever the first call stopped. path.read_text() is a shortcut for small files.

Example: three ways to read the same file

This example creates a three-line file in a temporary folder and reads it three different ways. repr() makes each \n visible, so you can see exactly which method keeps the newlines.

read_ways.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "readme.txt"
    path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")

    with open(path, encoding="utf-8") as f:
        content = f.read()              # the whole file as one string
    print(repr(content))

    with open(path, encoding="utf-8") as f:
        first = f.readline()            # one line, newline included
        rest = f.readlines()            # every remaining line, as a list
    print(repr(first))
    print(rest)

    with open(path, encoding="utf-8") as f:
        for number, line in enumerate(f, start=1):   # one line at a time
            print(number, line.rstrip("\n"))

Code breakdown

  1. Line 6path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")

    This creates the file to read. On Windows, text mode stores each \n as \r\n on disk, but reading in text mode turns it back into \n, so the output is identical on every system.

  2. Line 9content = f.read() # the whole file as one string

    read() returns a single str with all three \n characters inside it. Thanks to repr(), the output shows the quotes and the \n escapes.

  3. Lines 13-14rest = f.readlines() # every remaining line, as a list

    readline() reads the first line and leaves the cursor at the start of the second, so readlines() only gets the remaining two lines. Notice that "First line." is missing from the list.

  4. Lines 19-20for number, line in enumerate(f, start=1): # one line at a time

    The file object is itself an iterator, so the for loop takes one line per step. enumerate(..., start=1) numbers the lines from 1. Without rstrip("\n"), the line's own newline plus print()'s newline would leave a blank line between lines.

You should see
'First line.\nSecond line.\nThird line.\n'
'First line.\n'
['Second line.\n', 'Third line.\n']
1 First line.
2 Second line.
3 Third line.

Read CSV with the csv module

line.split(",") breaks a quoted value like "Smith, John" into two pieces. The csv module understands the quoting rules. As the csv documentation advises, open the file with newline="" so the module can handle newlines inside quoted fields itself. DictReader uses the first line as column names and gives you each row as a dict.

read_csv.py
import csv
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "people.csv"
    path.write_text('name,city\nAye,Yangon\n"Smith, John",Mandalay\n', encoding="utf-8")

    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            print(row["name"], "|", row["city"])

In real projects

Where this shows up in real projects

Scripts that ops teams write every day stream log files to count ERROR lines, tally requests per IP address, or pick out slow requests. Combining for line in f: with collections.Counter lets one pass over a multi-gigabyte file produce a summary using very little memory.

Data-import features read a user's uploaded CSV with csv.DictReader and treat every row as untrusted input: they check for missing columns, text where a number belongs, and wrong encodings, then report errors together with the row number. Reading the file is only the first step toward trustworthy data; validation is where the real work happens.

Config files are read the same way. For JSON settings you hand the open file object straight to json.load(f), and for TOML you use tomllib, part of the standard library since Python 3.11, with a file opened in "rb" mode. The parser does the reading, so you never split lines yourself.

Common mistakes

Common mistakes

1. Comparing lines without stripping the \n

if line == "admin": is never True even though users.txt contains admin, because the line is really "admin\n". Write line.strip() == "admin" instead.

2. Looping over the same file object twice

The first for loop leaves the cursor at the end, so a second loop over the same object runs zero times without any error. Call f.seek(0) before looping again, or store the lines in a list if the file is small.

3. Calling read() or readlines() on a huge file

Both read() and readlines() pull the entire file into memory, which is risky when you do not control the file's size. Read logs, exports and anything else that can grow with for line in f:.

Best practices

Best practices

  • Default to for line in f: whenever you do not control how big the file can get.
  • Use standard library modules for CSV, JSON and TOML instead of parsing them by hand.
  • Treat data read from a file as untrusted input and check its types and ranges.
  • Include line numbers in error messages; enumerate(f, start=1) makes that easy.

Mini challenge

Mini challenge: summarize a log file

Write summarize_log(), which streams a log of "LEVEL message" lines in one pass, counts the lines for each level, and collects the ERROR messages.

  • Read the file with for line in f:, never read() or readlines()
  • Skip blank lines
  • Count levels with collections.Counter
  • Create the log file inside a temporary directory
log_summary.py
import tempfile
from collections import Counter
from pathlib import Path

SAMPLE = (
    "INFO server started\n"
    "WARNING disk 85% full\n"
    "ERROR payment timeout order=17\n"
    "\n"
    "INFO request /home\n"
    "ERROR payment timeout order=21\n"
)


def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
    """Stream the log once: count lines per level and collect ERROR messages."""
    # TODO: open the file with utf-8 and loop over it line by line
    # TODO: strip each line, skip blank ones, split off the level
    # TODO: count the level; keep the message when the level is ERROR
    ...


# TODO: write SAMPLE to app.log in a temporary directory, summarize it, print results

Expected: The program prints: {'INFO': 2, 'WARNING': 1, 'ERROR': 2} ERROR: payment timeout order=17 ERROR: payment timeout order=21

Show hint

line.partition(" ") splits at the first space and returns (level, " ", message). A Counter lets you do counts[key] += 1 even for a key it has not seen yet.

Show solution
log_summary.py
import tempfile
from collections import Counter
from pathlib import Path

SAMPLE = (
    "INFO server started\n"
    "WARNING disk 85% full\n"
    "ERROR payment timeout order=17\n"
    "\n"
    "INFO request /home\n"
    "ERROR payment timeout order=21\n"
)


def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
    """Return a level -> count Counter and the list of ERROR messages."""
    levels: Counter[str] = Counter()
    errors: list[str] = []
    with open(path, encoding="utf-8") as f:
        for raw_line in f:
            line = raw_line.strip()
            if not line:
                continue                      # blank line
            level, _, message = line.partition(" ")
            levels[level] += 1
            if level == "ERROR":
                errors.append(message)
    return levels, errors


with tempfile.TemporaryDirectory() as tmp:
    log_path = Path(tmp) / "app.log"
    log_path.write_text(SAMPLE, encoding="utf-8")
    levels, errors = summarize_log(log_path)
    print(dict(levels))
    for message in errors:
        print("ERROR:", message)

Quick quiz 1 / 3

A file contains "a\nb\n". What do three calls to f.readline() in a row return?

Quick quiz 2 / 3

You call data = f.read() and then immediately lines = f.readlines() on the same file object. What is lines?

Quick quiz 3 / 3

Which approach is best for counting lines containing "timeout" in a 10 GB log?

What to remember

  • read() gives one str, readline() one line, readlines() a list, and for line in f: one line per step.
  • Every read moves the cursor forward and the end gives ""; call f.seek(0) to start over.
  • Lines keep their \n, so strip() before comparing.
  • Stream big files with for line in f:, and read CSV with the csv module.

Python Documentation — Reading and Writing Files — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Read Files | Thuta Learning