SyntaxStudy
Sign Up
Python Beginner 8 min read

Reading Files

Reading Files

Python's built-in open() function provides all you need to read files. Always use the with statement so the file is automatically closed.

Basic Read

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()        # entire file as one string
print(content)

readlines() & readline()

with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()     # list of strings (with \n)
    print(lines[0])

with open("data.txt", "r", encoding="utf-8") as f:
    first = f.readline()      # one line at a time

Iterating Line by Line (Memory Efficient)

with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:            # best for large files
        print(line.rstrip())

with Statement Details

# Equivalent without with:
f = open("data.txt", "r")
try:
    data = f.read()
finally:
    f.close()   # must close manually

Reading Binary Files

with open("image.png", "rb") as f:
    header = f.read(8)        # first 8 bytes
    print(header)
Example
# Create and read a file
import tempfile, os

# Write sample data
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False, encoding="utf-8")
tmp.write("Line 1
Line 2
Line 3
")
tmp.close()

with open(tmp.name, "r", encoding="utf-8") as f:
    for i, line in enumerate(f, 1):
        print(f"{i}: {line.rstrip()}")

os.unlink(tmp.name)
Pro Tip

Avoid read() on very large files — it loads everything into memory. Iterate line by line or use chunks: f.read(4096) in a loop.