For some reason I can't log into the same account on my home computer as my work computer.
I was able to get Bo10's code to work, but not abernert's and I would really like to understand why.
Here is my updates to abernert's code:
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'
So now I have the changed the code to this and the output is just repeating the names of the columns 322 times. I changed it on line 14 because i was getting this error:
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)
csv
is a bad idea, because it hides thecsv
module. That's especially true in this case, when you want to use thecsv
module—you can't docsv.writer
after you've donecsv = open(…)
. (Also, it's both simpler and more robust to use awith
statement instead of explicitopen
andclose
.) – abarnert Jun 27 at 0:09with open('output.csv', 'w') as csv_file:
, then put the code that usescsv_file
indented under thewith
, then you don't need to callclose
. – abarnert Jun 27 at 0:26with
statements than there is!) – abarnert Jun 27 at 0:29