Skip to content

Instantly share code, notes, and snippets.

@wp126
Last active August 24, 2022 12:39
Show Gist options
  • Save wp126/91fb76b79df8bd9b3118b89cf86fbc42 to your computer and use it in GitHub Desktop.
Save wp126/91fb76b79df8bd9b3118b89cf86fbc42 to your computer and use it in GitHub Desktop.
Convert Csv to Json in Python
import csv
import json
# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):
# create a dictionary
data = {}
x=0
# Open a csv reader called DictReader
with open(csvFilePath, encoding='unicode_escape') as csvf:
csvReader = csv.DictReader(csvf)
# Convert each row into a dictionary
# and add it to data
for rows in csvReader:
# Assuming a column named 'No' to
# be the primary key
key =x
data[key] = rows
x=x+1
# Open a json writer, and use the json.dumps()
# function to dump data
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
# Driver Code
# Decide the two file paths according to your
# computer system
csvFilePath = r'pincode.csv'
jsonFilePath = r'pincode.json'
# Call the make_json function
make_json(csvFilePath, jsonFilePath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment