read csv from a file and convert it to json in python

To read a CSV file and convert it to JSON in Python, you can use the csv and json modules that come with Python. Here's some example code:

main.py
import csv
import json

# Open the CSV file and read data
with open('data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)

    # Convert the CSV data to JSON
    data = []
    for row in reader:
        data.append(row)
    json_data = json.dumps(data)

# Write the JSON data to a file
with open('data.json', 'w') as jsonfile:
    jsonfile.write(json_data)
369 chars
17 lines

In this code, we use the csv.DictReader method to read data from the CSV file and store it as a list of dictionaries. We then use the json.dumps method to convert the list of dictionaries to a JSON-formatted string. Finally, we write the JSON data to a file using the open method with the 'w' flag to open the file in write mode.

gistlibby LogSnag