PY

File I/O

Python · 8 entries

Reading Files

syntax
with open(path, 'r') as f:
    content = f.read()
example
with open("config.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content[:50])

# Read line by line (memory efficient)
with open("data.log") as f:
    for line in f:
        print(line.strip())

Note Always specify encoding='utf-8' explicitly. The default varies by platform. Iterating line-by-line avoids loading the entire file into memory.

Writing Files

syntax
with open(path, 'w') as f:
    f.write(text)
example
lines = ["alice,95", "bob,82", "carol,91"]

with open("scores.csv", "w", encoding="utf-8") as f:
    f.write("name,score\n")
    for line in lines:
        f.write(line + "\n")

# Append mode
with open("scores.csv", "a") as f:
    f.write("dave,88\n")

Note 'w' mode truncates the file first. Use 'a' to append. Use 'x' to create exclusively (fails if file exists).

pathlib (Modern Path Handling)

syntax
from pathlib import Path
example
from pathlib import Path

data_dir = Path("project") / "data"
data_dir.mkdir(parents=True, exist_ok=True)

config = data_dir / "settings.json"
config.write_text('{"debug": true}', encoding="utf-8")
print(config.read_text())
print(config.suffix, config.stem)
output
{"debug": true}
.json settings

Note pathlib is the modern replacement for os.path. The / operator joins paths. Use .resolve() for absolute paths, .exists() to check existence.

CSV Files

syntax
import csv
example
import csv

# Writing
with open("users.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerow({"name": "Alice", "age": 30})
    writer.writerow({"name": "Bob", "age": 25})

# Reading
with open("users.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["age"])
output
Alice 30
Bob 25

Note Always pass newline='' when opening CSV files (the csv module handles line endings itself). DictReader/DictWriter are more readable than plain reader/writer.

JSON Files

syntax
import json
json.dump(obj, file)
obj = json.load(file)
example
import json
from pathlib import Path

config = {"host": "localhost", "port": 8080, "debug": True}

# Write
Path("config.json").write_text(
    json.dumps(config, indent=2), encoding="utf-8"
)

# Read
loaded = json.loads(Path("config.json").read_text())
print(loaded["port"])
output
8080

Note json.dump/load work with file objects. json.dumps/loads work with strings. Use indent= for readable output. Python dicts serialize directly to JSON objects.

Binary File I/O

syntax
with open(path, 'rb') as f:
    data = f.read()
example
# Copy a binary file
with open("image.png", "rb") as src:
    data = src.read()

with open("copy.png", "wb") as dst:
    dst.write(data)

print(f"Copied {len(data)} bytes")

Note Use 'rb' / 'wb' modes for binary files (images, archives, etc.). Never open binary files in text mode; it corrupts the data on some platforms.

Context Managers (with Statement)

syntax
with expression as variable:
    ...
example
from contextlib import contextmanager

@contextmanager
def temp_directory():
    import tempfile, shutil
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        shutil.rmtree(path)

with temp_directory() as tmp:
    print(f"Working in {tmp}")

Note The with statement guarantees cleanup code runs even if an exception occurs. Use contextlib.contextmanager to build custom context managers from generators.

Finding Files with Glob

syntax
Path(dir).glob(pattern)
Path(dir).rglob(pattern)
example
from pathlib import Path

# All Python files in current directory
for py_file in Path(".").glob("*.py"):
    print(py_file.name)

# Recursive search
all_json = list(Path(".").rglob("*.json"))
print(f"Found {len(all_json)} JSON files")

Note glob() searches one level. rglob() searches recursively through all subdirectories. Both return Path objects.