You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
2 years ago
|
|
||
|
import csv
|
||
|
import json
|
||
|
|
||
|
# Modified from https://www.geeksforgeeks.org/convert-csv-to-json-using-python/
|
||
|
|
||
|
# Function to convert a CSV to JSON
|
||
|
# Takes the file paths as arguments
|
||
|
def make_json(csvFilePath, jsonFilePath):
|
||
|
|
||
|
# create a dictionary
|
||
|
dictionary = {}
|
||
|
|
||
|
# Open a csv reader called DictReader
|
||
|
with open(csvFilePath, encoding='utf-8') 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 'English' to
|
||
|
# be the primary key
|
||
|
key = rows['English']
|
||
|
print("key is {}".format(key))
|
||
|
value = rows['Japanese']
|
||
|
print("value is {}".format(value))
|
||
|
dictionary[key] = value
|
||
|
|
||
|
# 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(dictionary, ensure_ascii=False, indent=4))
|
||
|
|
||
|
# Driver Code
|
||
|
|
||
|
# Decide the two file paths according to your
|
||
|
# computer system
|
||
|
csvFilePath = r'dictionary.csv'
|
||
|
jsonFilePath = r'dictionary.json'
|
||
|
|
||
|
# Call the make_json function
|
||
|
make_json(csvFilePath, jsonFilePath)
|
||
|
|
||
|
|
||
|
# interesting project on pokemon csv
|
||
|
# https://amiradata.com/parse-and-convert-json-to-csv-python/
|