Created
August 12, 2014 11:10
-
-
Save pythononwheels/7631d8c8e3fadcb77393 to your computer and use it in GitHub Desktop.
Short python utility that converts a given csv to the according json. Fieldnames are taken from the first line of the csv.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import json | |
import sys | |
# | |
# | |
# converts csv to json | |
# fieldnames are taken from the first line of the csv input file | |
# | |
# khz / 2014 | |
# | |
if __name__ == "__main__": | |
#print(sys.argv, len(sys.argv)) | |
filename = None | |
if len(sys.argv) < 2: | |
print("usage: csv_to_json.py <filename> ") | |
print(" You dont need to give a file extension. The tool automatically adds .csv and .json") | |
sys.exit() | |
else: | |
filename = sys.argv[1] | |
csvfile = open(filename + '.csv', 'r', encoding="utf8") | |
fieldnames = list(csvfile.readline().split(",")) | |
jsonfile = open(filename + '.json', 'w') | |
reader = csv.DictReader( csvfile, fieldnames) | |
for row in reader: | |
json.dump(row, jsonfile) | |
jsonfile.write('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added an encoding to the open() call to make sure that python3 unicode errors wont occur.