为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Python将JSON解析为CSV中的两列

如何使用Python将JSON解析为CSV中的两列

呼如林 2021-04-05 03:43:17
由于某种原因,我无法在家用计算机上登录与工作计算机相同的帐户。我能够使Bo10的代码正常工作,但不能使abernert的代码正常工作,我真的很想知道为什么。这是我对abernert代码的更新:    import csv    import sys    import json    import urllib2    j = urllib2.urlopen('https://citibikenyc.com/stations/json')    js = json.load(j)    citi = js['stationBeanList']    columns = ('stationName', 'totalDocks', 'availableDocks',                'latitude', 'longitude', 'availableBikes')    stations = (operator.itemgetter(columns)(station) for station in citi)    with open('output.csv', 'w') as csv_file:        csv_writer = csv.writer(csv_file)        csv_file.writerows(stations)I thought adding this line `csv_writer = csv.writer(csv_file)` would fix the object has no attirbute error, but I am still getting it.  This is the actual error:Andrews-MacBook:coding Andrew$ python citibike1.pyTraceback (most recent call last):  File "citibike1.py", line 17, in <module>    csv_file.writerows(stations)AttributeError: 'file' object has no attribute 'writerows'因此,现在我将代码更改为此,并且输出仅将列的名称重复322次。我在第14行上更改了它,因为出现了此错误:Traceback (most recent call last):  File "citibike1.py", line 17, in <module>    csv_writer.writerows(stations)  File "citibike1.py", line 13, in <genexpr>    stations = (operator.itemgetter(columns)(station) for station in citi)NameError: global name 'operator' is not defined: import csvimport sysimport jsonimport urllib2import operatorj = urllib2.urlopen('https://citibikenyc.com/stations/json')js = json.load(j)citi = js['stationBeanList']columns = ('stationName', 'totalDocks', 'availableDocks',            'latitude', 'longitude', 'availableBikes')stations = (operator.itemgetter(0,1,2,3,4,5)(columns) for station in citi)with open('output.csv', 'w') as csv_file:    csv_writer = csv.writer(csv_file)    csv_writer.writerows(stations)
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 276 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信