由于某种原因,我无法在我的家用计算机上登录与我的工作计算机相同的帐户。
我能够让 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.py
Traceback (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 csv
import sys
import json
import urllib2
import operator
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(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)