How would you work with CSV or JSON files in Python?

Working with CSV and JSON files in Python is straightforward, thanks to the built-in libraries and third-party modules available. Here’s a guide for each format:


Working with CSV Files

Python provides the csv module to handle CSV files efficiently.

Reading a CSV File

import csv

# Open the CSV file
with open('data.csv', mode='r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # Each row is a list

Writing to a CSV File

import csv

# Open the file in write mode
with open('data.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', 30, 'New York'])
    writer.writerow(['Bob', 25, 'Los Angeles'])

Using a DictReader and DictWriter

# Reading as dictionaries
with open('data.csv', mode='r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)  # Each row is an OrderedDict

# Writing dictionaries
with open('data.csv', mode='w', newline='') as file:
    fieldnames = ['Name', 'Age', 'City']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'Alice', 'Age': 30, 'City': 'New York'})
    writer.writerow({'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'})

Working with JSON Files

Python provides the json module to parse and generate JSON data.

Reading a JSON File

import json

# Open the JSON file
with open('data.json', mode='r') as file:
    data = json.load(file)  # Deserialize JSON to Python object
    print(data)

Writing to a JSON File

import json

# Python dictionary
data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Write JSON to a file
with open('data.json', mode='w') as file:
    json.dump(data, file, indent=4)  # Serialize Python object to JSON

Working with JSON Strings

# JSON string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'

# Deserialize JSON string to Python object
data = json.loads(json_string)
print(data)

# Serialize Python object to JSON string
json_string = json.dumps(data, indent=4)
print(json_string)

Using Pandas for CSV and JSON

If you’re working with structured data and want more powerful tools, consider using Pandas.

Install Pandas:

pip install pandas

Read CSV:

import pandas as pd

df = pd.read_csv('data.csv')
print(df)

Write CSV:

df.to_csv('data.csv', index=False)

Read JSON:

df = pd.read_json('data.json')
print(df)

Write JSON:

df.to_json('data.json', orient='records', indent=4)

By leveraging these tools, you can efficiently read, write, and manipulate both CSV and JSON files in Python.

My Thought

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

Our Tool : hike percentage calculator