fbpx

Working with CSV and JSON Files in Python

Working with CSV (Comma-Separated Values) and JSON (JavaScript Object Notation) files is common in Python for handling structured data. Let’s explore how to read and write data to these file formats.


1. Working with CSV Files:

1.1 Reading from a CSV File:

Python provides the csv module to work with CSV files. Here’s how you can read data from a CSV file:

import csv

# Reading from a CSV file
with open("data.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file)

    # Iterate through rows
    for row in csv_reader:
        print(row)

1.2 Writing to a CSV File:

To write data to a CSV file, you can use the csv.writer class:

import csv

# Writing to a CSV file
data_to_write = [
    ["Name", "Age", "City"],
    ["Alice", 25, "Wonderland"],
    ["Bob", 30, "TechCity"]
]

with open("output.csv", "w", newline="") as csv_file:
    csv_writer = csv.writer(csv_file)

    # Write rows
    csv_writer.writerows(data_to_write)

2. Working with JSON Files:

2.1 Reading from a JSON File:

Python has built-in support for JSON through the json module. To read data from a JSON file:

import json

# Reading from a JSON file
with open("data.json", "r") as json_file:
    data = json.load(json_file)
    print(data)

2.2 Writing to a JSON File:

To write data to a JSON file, you can use the json.dump method:

import json

# Writing to a JSON file
data_to_write = {
    "name": "Alice",
    "age": 25,
    "city": "Wonderland"
}

with open("output.json", "w") as json_file:
    json.dump(data_to_write, json_file, indent=2)

3. Dealing with Nested Structures:

Both CSV and JSON support nested data structures. For CSV, you might use a delimiter other than a comma for more complex structures. For JSON, nested dictionaries or lists are commonly used.

4. Handling Errors:

It’s essential to handle errors when working with files, especially when dealing with user input for file paths or unexpected file content.

import csv
import json

try:
    with open("data.csv", "r") as csv_file:
        csv_reader = csv.reader(csv_file)
        for row in csv_reader:
            print(row)
except FileNotFoundError:
    print("The CSV file does not exist.")
except Exception as e:
    print(f"An error occurred: {e}")

5. Conclusion:

Working with CSV and JSON files is a fundamental skill for data processing and exchange. Whether you’re dealing with tabular data or structured information, Python provides convenient modules to handle these file formats efficiently.

In the next sections, we’ll explore more advanced topics and practical applications of working with data in Python.