Back to Python tutorials
Basic15 min read

File I/O & Modules

Read and write files safely and organize code into modules and packages.

Reading and Writing Files

open(path, mode, encoding="utf-8") returns file objects. Use with statements for automatic close even on exceptions.

Text mode handles encoding/decoding; binary mode reads bytes for images and PDFs. pathlib.Path offers ergonomic path operations cross-platform.

For large files, iterate line by line instead of read() entire content into memory.

  • Always specify encoding for text files on Windows
  • Use tempfile for sensitive scratch files
  • Check path.exists() before optional reads
from pathlib import Path

config = Path("config.toml").read_text(encoding="utf-8")
Path("out.json").write_text(json.dumps(data), encoding="utf-8")

Modules and Packages

Each .py file is a module; folders with __init__.py are packages. import loads modules once into sys.modules cache.

Relative imports work inside packages: from .models import User. Absolute imports from project root are clearer in apps.

__all__ lists public API names for from package import * though explicit imports are preferred.

  • Avoid circular imports by extracting shared interfaces
  • Use pyproject.toml for modern package metadata
  • Run python -m package.module for correct sys.path
# myapp/services/users.py
from myapp.models import User

def get_user(user_id: int) -> User:
    ...

Get In Touch


Ready to discuss your next project? Drop me a message.