-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv2json.py
51 lines (38 loc) · 1.15 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
49
50
51
import sys
import json
import csv
def main():
if sys.argv[1] == 'help':
printHelp()
else:
convert2json()
def convert2json():
separator = ","
try:
separator = str(sys.argv[4])
except:
pass
try:
datamodelfile = csv.reader(open(sys.argv[1], "rU"), delimiter=separator, dialect="excel")
datafile = open(sys.argv[2], "rU")
outfile = open(sys.argv[3], 'a')
except:
print "The parameters for this script are: csv_data_model_file csv_input_data_file output_file separator"
datamodel = []
for row in datamodelfile:
datamodel = row
data = csv.reader(datafile, delimiter=separator)
for row in data:
if len(row) == len(datamodel):
dic = {}
for i in range(len(datamodel)):
dic[datamodel[i]] = row[i]
json.dump(dic, outfile, sort_keys=True)
outfile.write('\n')
else:
print "Datamodel does not correspond with the data"
def printHelp():
helptext = open('README.md').read()
print helptext
if __name__ == '__main__':
main()