-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv2json.py
48 lines (43 loc) · 1.49 KB
/
csv2json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python
import sys, getopt
import csv
import json
#Get Command Line Arguments
def main(argv):
input_file = ''
output_file = ''
format = ''
try:
opts, args = getopt.getopt(argv,"hi:o:f:",["ifile=","ofile=","format="])
except getopt.GetoptError:
print ('csv_json.py -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('csv_json.py -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>')
sys.exit()
elif opt in ("-i", "--ifile"):
input_file = arg
elif opt in ("-o", "--ofile"):
output_file = arg
elif opt in ("-f", "--format"):
format = arg
read_csv(input_file, output_file, format)
#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file, 'rU') as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
write_json(csv_rows, json_file, format)
#Convert csv data into json and write it
def write_json(data, json_file, format):
with open(json_file, "w") as f:
if format == "pretty":
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),ensure_ascii=False))
else:
f.write(json.dumps(data))
if __name__ == "__main__":
main(sys.argv[1:])