</>
Skip to content
Python lessons (39/45)

Python — Read Files

The whole file at once

with open("notes.txt", encoding="utf-8") as f:
    text = f.read()          # one big string

print(len(text))             # character count

Fine for small files (config, templates). A 2GB log would eat your RAM.

Line by line — the memory-safe default

The file object IS iterable:

with open("big.log", encoding="utf-8") as f:
    for line in f:           # streams one line at a time
        if "ERROR" in line:
            print(line.rstrip())   # rstrip removes the trailing \n

Handles gigabyte files with constant memory.

readlines vs readline

f.readlines()    # → ["line1\n", "line2\n"]  list of all (memory!)
f.readline()     # → next single line each call; "" when done

Cleaning newlines

Every line keeps its \n:

for line in f:
    line = line.strip()          # kills \n AND surrounding spaces
    # or keep interior spacing with .rstrip("\n")

Parsing structured lines

scores = {}
with open("scores.csv") as f:
    header = f.readline()                    # skip header row
    for line in f:
        name, score = line.strip().split(",")
        scores[name] = int(score)

Chunked binary reads

with open("movie.mp4", "rb") as src:
    while chunk := src.read(1024 * 1024):    # 1MB at a time (walrus!)
        process(chunk)

The walrus operator assigns and tests in one expression — clean copy loops.

Reading JSON/CSV the smart way

Structured formats have dedicated readers:

import json
config = json.load(open("config.json"))      # parses for you

import csv
with open("users.csv", newline="") as f:
    for row in csv.DictReader(f):            # dicts per row!
        print(row["email"])

Which reader when

NeedMethod
Config/template, small fileread()
Huge/streaming logsfor line in f
List of lines to mutatereadlines()
Binary mediaread(chunk) loop
CSV/JSON datacsv / json modules

Mini Practice

  1. Count words across a whole text file.
  2. Print only lines containing "TODO".
  3. Parse a two-column file into a dict.
  4. Copy a file 1MB-chunk-at-a-time.
  5. Load a JSON config with defaults on FileNotFoundError.

Next: write/create files →

Related Topics

Frequently Asked Questions about Read Files

What is Read Files in Python?

Read Files is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Read Files?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Read Files.

Why is Read Files important in Python?

Read Files is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.