.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-inopen() function to read and write them.
Reading Text Files
Always use thewith 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-injson module handles serialisation (Python → JSON string) and deserialisation (JSON string → Python).
JSON ↔ Python Type Mapping
Core Functions
JSON in Practice
Handling CSV Data
CSV (Comma-Separated Values) is the standard format for spreadsheets and tabular data. Python’scsv module provides both simple list-based and dictionary-based readers and writers.
Reading CSV Files
As lists (one row = one list of strings):Writing CSV Files
Always pass
newline="" when opening a CSV file for writing on Windows to prevent extra blank lines from appearing between rows.