📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero File I/O

File I/O

5 min read
Open files safely with with open('file.txt') as f: — it closes automatically. Use read() for full content or iterate with for line in f. Use json.load() and json.dump() for JSON files.

Reading and Writing Files

# Write
with open("data.txt", "w") as f:
    f.write("Hello, file!")

# Read all
with open("data.txt") as f:
    content = f.read()

# Read lines
with open("data.txt") as f:
    for line in f:
        print(line.strip())

# JSON
import json
with open("data.json", "w") as f:
    json.dump({"key": "value"}, f)