-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathto_csv.py
More file actions
55 lines (51 loc) · 1.62 KB
/
to_csv.py
File metadata and controls
55 lines (51 loc) · 1.62 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
import csv
import sys
import json
json_file_name = sys.argv[1]
csv_file_name = sys.argv[2]
keys = (
"id",
"name",
"symbol",
"rank",
"price_usd",
"price_btc",
"24h_volume_usd",
"market_cap_usd",
"available_supply",
"total_supply",
"max_supply",
"percent_change_1h",
"percent_change_24h",
"percent_change_7d",
"last_updated"
)
# csv_file is only valid inside the with block.
with open(csv_file_name, 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=keys, delimiter=',', lineterminator='\n')
csv_writer.writeheader()
with open(json_file_name, 'r') as json_file:
json_data = json.loads(json_file.read())
for currency in json_data:
csv_writer.writerow(currency)
"""
# csv_file is valid anywhere after this line.
csv_file = open(csv_file_name, 'w')
csv_writer = csv.DictWriter(csv_file, fieldnames=keys, delimiter=',', lineterminator='\n')
csv_writer.writeheader()
json_file = open(json_file_name, 'r')
json_data = json.loads(json_file.read())
for currency in json_data:
csv_writer.writerow(currency)
# This is like the one above but using csv_file.write rather than th csv module.
with open(csv_file_name, 'w') as csv_file:
headers_row = ','.join(keys)
csv_file.write(headers_row)
csv_file.write('\n')
with open(json_file_name, 'r') as json_file:
json_data = json.loads(json_file.read())
for currency in json_data:
row = ','.join((currency[key] or '' for key in keys))
csv_file.write(row)
csv_file.write('\n')
"""