Skip to main content
Programs exist to process data. Whether you’re loading a configuration file, consuming a REST API, or analysing a spreadsheet, Python gives you everything you need in the standard library — no extra packages required. This page covers three of the most common data formats you’ll encounter: plain text (.txt), JSON (the universal API format), and CSV (tabular/spreadsheet data). You’ll learn to read, manipulate, and save each format using clean, Pythonic patterns.

Handling Text Data

Plain text files are the simplest format. Python provides the built-in open() function to read and write them.

Reading Text Files

Always use the with statement — it automatically closes the file even if an exception occurs:

Writing Text Files

Use "w" to overwrite the file (creates it if it doesn’t exist) or "a" to append:
If you open a file with "w" and it already exists, its contents are erased before writing. Use "a" when you want to add to the end of an existing file.

Handling JSON Data

JSON (JavaScript Object Notation) is the standard format for web APIs and configuration files. Python’s built-in json module handles serialisation (Python → JSON string) and deserialisation (JSON string → Python).

JSON ↔ Python Type Mapping

Core Functions

JSON in Practice

Use indent=4 in json.dumps() and json.dump() to produce human-readable, pretty-printed JSON. For compact machine-to-machine transfer, omit the indent argument.

Handling CSV Data

CSV (Comma-Separated Values) is the standard format for spreadsheets and tabular data. Python’s csv module provides both simple list-based and dictionary-based readers and writers.

Reading CSV Files

As lists (one row = one list of strings):
As dictionaries — recommended because column names become keys:

Writing CSV Files

Always pass newline="" when opening a CSV file for writing on Windows to prevent extra blank lines from appearing between rows.

Choosing the Right Format