Skip to main content
Almost every real program needs to read data from somewhere and write results somewhere else. Python’s standard library gives you everything you need to work with text files, JSON APIs, CSV spreadsheets, dates, and file paths — no third-party packages required. This page walks you through each format with practical, copy-paste-ready examples.

Text Files with open()

The built-in open() function is your entry point for all file I/O. Always pair it with a with statement — it guarantees the file is closed when the block exits, even if an exception is raised.

File Modes

Reading

Writing and Appending

Always specify encoding="utf-8" when reading or writing text files that may contain non-ASCII characters (names, addresses, product descriptions). The default encoding varies by operating system.

JSON with the json Module

JSON is the lingua franca of web APIs and configuration files. Python’s json module converts seamlessly between Python objects and JSON strings.

The Four Core Functions

Serialisation and Deserialisation

Reading and Writing JSON Files

JSON ↔ Python Type Mapping

CSV with the csv Module

CSV (Comma-Separated Values) is the standard format for spreadsheets and tabular exports. Python’s csv module handles quoting, escaping, and newlines correctly so you don’t have to.

Reading CSV as Rows (Lists)

DictReader uses the header row as keys, giving you named access to each field:

Writing CSV

Always open CSV files with newline="". If you don’t, the csv module may mishandle line endings on Windows, producing extra blank rows in your output.

Dates and Times with datetime

Modern Path Handling with pathlib

pathlib.Path is the modern, object-oriented way to work with file system paths. It replaces most uses of os.path with a much cleaner API.

Practical Example: Read a Config + Process a CSV

Here’s a complete workflow that ties everything together — load a JSON config, then process a CSV data file respecting those config settings: