forked from nkmk/e-stat-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_get_stats_data.py
More file actions
40 lines (28 loc) · 978 Bytes
/
example_get_stats_data.py
File metadata and controls
40 lines (28 loc) · 978 Bytes
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
import urllib.request
import urllib.parse
import json
with open('setting/get_stats_data_sample.json') as f:
print(f.read())
# {
# "statsDataId": "0003215840"
# }
with open('setting/get_stats_data_sample.json') as f:
p = json.load(f)
with open('setting/app_id.json') as f:
p_id = json.load(f)
p.update(p_id)
url = ('http://api.e-stat.go.jp/rest/2.1/app/getSimpleStatsData?'
+ urllib.parse.urlencode(p))
with urllib.request.urlopen(url) as response:
data = response.read()
print(type(data))
# <class 'bytes'>
with open('download/stats_data_{}_header.csv'.format(p['statsDataId']), 'w') as f:
f.write(data.decode())
p['sectionHeaderFlg'] = 2
url = ('http://api.e-stat.go.jp/rest/2.1/app/getSimpleStatsData?'
+ urllib.parse.urlencode(p))
with urllib.request.urlopen(url) as response:
data = response.read()
with open('download/stats_data_{}.csv'.format(p['statsDataId']), 'w') as f:
f.write(data.decode().split('\n', 1)[1])