iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Read Files

There are three common ways to read a file. Pick based on size and how you want to process the contents.

All at once

PYTHON
with open('hello.txt') as f:
    text = f.read()
print(text)

Fine for small files. Bad for multi-gigabyte ones.

Line by line — the streaming way

PYTHON
with open('big.log') as f:
    for line in f:
        if 'ERROR' in line:
            print(line.rstrip())

Memory-friendly. Works on files larger than RAM.

Into a list

PYTHON
with open('hello.txt') as f:
    lines = f.readlines()   # includes trailing newlines
print(lines[0].rstrip())

Read N characters / bytes

PYTHON
with open('hello.txt') as f:
    chunk = f.read(100)     # first 100 chars
    next_chunk = f.read(100)

CSV — use the right module

PYTHON
import csv
with open('users.csv', newline='') as f:
    for row in csv.DictReader(f):
        print(row['name'], row['email'])

JSON

PYTHON
import json
with open('users.json') as f:
    users = json.load(f)
Tip: For real CSV (quoted fields, commas inside values) always use the csv module. Splitting on commas yourself breaks the first time someone writes "Smith, Inc.".

Example

Example
# with open('hello.txt') as f:
#     for line in f:
#         print(line.rstrip())
# All in one go:
# print(open('hello.txt').read())
print('Use a with-block so the file closes automatically.')
Try it Yourself »

Exercise

Read the entire file as one string.

text = f. ()

Test yourself

Q1. For huge files prefer…
Q2. For CSV use…
Q3. readlines() returns…

Discussion

Loading…