Skip to content

Instantly share code, notes, and snippets.

@awesomebjt
Created August 20, 2015 18:47
Show Gist options
  • Save awesomebjt/713965cd27a4257e30d7 to your computer and use it in GitHub Desktop.
Save awesomebjt/713965cd27a4257e30d7 to your computer and use it in GitHub Desktop.
CSV to JSON in Python
import csv
import json
import sys
#Expects argument 1 to be a .csv filename. Matching file ending in .json is written.
if sys.argv[1] is not None and len(sys.argv[1])>0:
infile = open(sys.argv[1],'r')
outfile = open(sys.argv[1].replace(".csv",".json"),'w')
reader = csv.reader(infile)
colnames = []
output_array = []
for row in reader:
out_dict = {}
if reader.line_num == 1: #Assume the columns have names.
colnames = row
else:
for colnum in range(len(row)):
out_dict[colnames[colnum]] = row[colnum]
output_array.append(out_dict)
outfile.write(json.dumps(output_array))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment