> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Working with Data Files: Text, JSON & CSV in Python

> Read, write, and process plain text files, JSON API payloads, and CSV spreadsheets using only Python's built-in standard library tools.

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:

```python theme={null}
# Read the entire file at once
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)

# Read line-by-line (memory-efficient for large files)
with open("sample.txt", "r") as file:
    for line in file:
        print(line.strip())   # .strip() removes trailing newlines
```

### Writing Text Files

Use `"w"` to overwrite the file (creates it if it doesn't exist) or `"a"` to append:

```python theme={null}
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Writing data is easy in Python.")
```

<Note>
  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.
</Note>

## 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

| JSON             | Python           |
| ---------------- | ---------------- |
| Object `{}`      | `dict`           |
| Array `[]`       | `list`           |
| String           | `str`            |
| Number           | `int` / `float`  |
| `true` / `false` | `True` / `False` |
| `null`           | `None`           |

### Core Functions

| Function            | Purpose                      |
| ------------------- | ---------------------------- |
| `json.loads(s)`     | JSON string → Python object  |
| `json.dumps(obj)`   | Python object → JSON string  |
| `json.load(f)`      | Read JSON from a file object |
| `json.dump(obj, f)` | Write JSON to a file object  |

### JSON in Practice

```python theme={null}
import json

user_profile = {
    "name": "Alice",
    "age": 25,
    "skills": ["Python", "Machine Learning"],
    "is_active": True
}

# 1. Serialise (Dict → JSON string)
json_string = json.dumps(user_profile, indent=4)
print(json_string)

# 2. Deserialise (JSON string → Dict)
data_dict = json.loads(json_string)
print(data_dict["name"])     # Alice

# 3. Write JSON to a file
with open("profile.json", "w") as file:
    json.dump(user_profile, file, indent=4)

# 4. Read JSON from a file
with open("profile.json", "r") as file:
    loaded_data = json.load(file)
    print(loaded_data["skills"])   # ['Python', 'Machine Learning']
```

<Tip>
  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.
</Tip>

## 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):

```python theme={null}
import csv

with open("employees.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)   # ['Name', 'Age', 'Role']
```

**As dictionaries** — recommended because column names become keys:

```python theme={null}
import csv

with open("employees.csv", "r") as file:
    dict_reader = csv.DictReader(file)
    for row in dict_reader:
        print(f"Name: {row['Name']}, Role: {row['Role']}")
```

### Writing CSV Files

```python theme={null}
import csv

fieldnames = ["Product", "Price", "Stock"]
products = [
    {"Product": "Laptop", "Price": 999.99, "Stock": 10},
    {"Product": "Mouse",  "Price": 29.99,  "Stock": 50}
]

with open("inventory.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()     # writes the column names row
    writer.writerows(products)
```

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

## Choosing the Right Format

| Use case                             | Format          |
| ------------------------------------ | --------------- |
| Configuration or human-readable logs | Text (`.txt`)   |
| REST API payloads and responses      | JSON            |
| Spreadsheets, data exports, reports  | CSV             |
| Structured data with validation      | JSON + Pydantic |
