-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy-csv-json-cli.py
More file actions
63 lines (41 loc) · 1.61 KB
/
py-csv-json-cli.py
File metadata and controls
63 lines (41 loc) · 1.61 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
import fire
class ConvertCsvJson(object):
def __init__(self):
import datetime
curr_dt = datetime.datetime.now()
self._timestamp = int(round(curr_dt.timestamp()))
def jsontocsv(self,jsonFilePath):
import csv
import json
if not jsonFilePath.endswith('.json'):
return "Error: Invalid JSON file!"
csvOutputFile = f"jsontocsv-{self._timestamp}.csv"
with open(jsonFilePath) as jsonf:
jsondata = json.load(jsonf)
data_file = open(csvOutputFile, 'w', newline='')
csv_writer = csv.writer(data_file)
count = 0
for data in jsondata:
if count == 0:
header = data.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(data.values())
data_file.close()
return f"Successfully created {csvOutputFile}"
def csvtojson(self,csvFilePath):
import csv
import json
if not csvFilePath.endswith('.csv'):
return "Error: Invalid CSV file!"
jsonOutputFile = f"csvtojson-{self._timestamp}.json"
data = []
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for rows in csvReader:
data.append(rows)
with open(jsonOutputFile, 'a', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
return f"Successfully created {jsonOutputFile}"
if __name__ == '__main__':
fire.Fire(ConvertCsvJson)