Working with CSV and JSON Files in Python

Loading

Working with CSV and JSON files in Python is straightforward, thanks to built-in libraries like csv and json. Here’s a breakdown of how to read and write these file formats.


Working with CSV Files

CSV (Comma-Separated Values) files store tabular data in plain text.

Reading a CSV File

Python provides the csv module to handle CSV files.

import csv

# Open CSV file and read content
with open("data.csv", mode="r", newline='', encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # Each row is a list

If the CSV file has headers, use DictReader to read them as dictionaries.

with open("data.csv", mode="r", newline='', encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)  # Each row is a dictionary

Writing to a CSV File

You can write lists of data to a CSV file using csv.writer.

data = [["Name", "Age", "City"], ["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"]]

with open("output.csv", mode="w", newline='', encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)  # Write multiple rows

If using dictionaries, DictWriter ensures proper handling of field names.

data = [
    {"Name": "Alice", "Age": 25, "City": "New York"},
    {"Name": "Bob", "Age": 30, "City": "Los Angeles"}
]

with open("output.csv", mode="w", newline='', encoding="utf-8") as file:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    
    writer.writeheader()  # Write column headers
    writer.writerows(data)  # Write dictionary rows

Working with JSON Files

JSON (JavaScript Object Notation) is commonly used for structured data exchange.

Reading a JSON File

Use the json module to read JSON data.

import json

with open("data.json", mode="r", encoding="utf-8") as file:
    data = json.load(file)  # Load JSON as a Python dictionary or list
    print(data)

Writing to a JSON File

To save data in JSON format:

data = {"name": "Alice", "age": 25, "city": "New York"}

with open("output.json", mode="w", encoding="utf-8") as file:
    json.dump(data, file, indent=4)  # Pretty-print with indentations

Converting Between CSV and JSON

Convert CSV to JSON:

import csv
import json

with open("data.csv", mode="r", encoding="utf-8") as csv_file:
    reader = csv.DictReader(csv_file)
    data = list(reader)

with open("output.json", mode="w", encoding="utf-8") as json_file:
    json.dump(data, json_file, indent=4)

Convert JSON to CSV:

import json
import csv

with open("data.json", mode="r", encoding="utf-8") as json_file:
    data = json.load(json_file)

with open("output.csv", mode="w", newline='', encoding="utf-8") as csv_file:
    fieldnames = data[0].keys()
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    
    writer.writeheader()
    writer.writerows(data)

Summary

OperationCSV (csv module)JSON (json module)
Readcsv.reader() or DictReader()json.load()
Writecsv.writer() or DictWriter()json.dump()
Convert CSV to JSONRead CSV, then use json.dump()
Convert JSON to CSVRead JSON, then use csv.DictWriter()

Would you like any additional explanations or examples?

Leave a Reply

Your email address will not be published. Required fields are marked *