Python Glossary Русский

all Python 3Files & I/Oterm

Iterating over a file

reading

A file object is iterable. Every iteration yields one line. Efficient for large files.

Syntax

for line in f:
    ...

Each line arrives with its trailing newline attached, which is why it is almost always cleaned up with strip() or rstrip('\n') — though the final line of a file may have no '\n' at all. The iterator is lazy and single-pass: once the loop ends the file is exhausted, and a second for over the same object yields nothing until you call f.seek(0). That laziness is exactly what separates this from f.readlines() or f.read().split('\n'), which pull the whole file into memory.

Examples

# Пример создаёт файл сам и работает во временной папке:
# путь вроде '/tmp/demo.txt' есть не на всякой системе.
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open('demo.txt', 'w', encoding='utf-8') as f:
    f.write('line1\nline2\nline3\n')
# Построчный обход: файл — итератор, вся целиком в память он не читается
with open('demo.txt', encoding='utf-8') as f:
    print([line.strip() for line in f])  # → ['line1', 'line2', 'line3']
# Фильтрация строк
with open('demo.txt', encoding='utf-8') as f:
    lines = [line.strip() for line in f if line.strip()]
print(lines)  # → ['line1', 'line2', 'line3']
# Подсчёт строк
with open('demo.txt', encoding='utf-8') as f:
    count = sum(1 for _ in f)
print(count)  # → 3
# Первые N строк
with open('demo.txt', encoding='utf-8') as f:
    head = [next(f) for _ in range(2)]
print([line.strip() for line in head])  # → ['line1', 'line2']
# enumerate для нумерации строк
with open('demo.txt', encoding='utf-8') as f:
    numbered = [f'{i}: {line.strip()}' for i, line in enumerate(f, 1)]
print(numbered)  # → ['1: line1', '2: line2', '3: line3']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy