[Tutor] Writing for loop output to csv
Peter Otten
__peter__ at web.de
Fri Sep 7 02:45:23 EDT 2018
Cameron Simpson wrote:
> On 06Sep2018 12:32, Brandon Creech <bdcreech91 at gmail.com> wrote:
>>Hi, I am working to forecast the temperatures for the next 5 days using an
>>API and a for loop. I would like write the output of this loop to a csv in
>>this format::
>>
>>Columns: City, min1, max1, min2, max2,min3,max3,min4,max4,min5,max5
>>data: Athens,Greece 25.4,26.7....etc.
>> Nantou,Taiwan 16.18, ......etc
> print call for the output. The csv module provides a writer object which
> does all the heavy lifting for you: turns strings into quotes strings,
> puts in commas, etc. Try this change:
>
> csvw = csv.writer(sys.stdout)
> for city, coords in cities.items():
> weather = ForecastIO.ForecastIO( api_key, latitude=coords[0],
> longitude=coords[1] )
> daily = FIODaily.FIODaily(weather)
> for day in range(2,7):
> day_data = daily.get_day(day)
> csvw.writerow([city, day_data['temperatureMax'],
> day_data['temperatureMin']])
If you want all min/max pairs in the same row you can prebuild that row in a
list. With minimal changes to Cameron's code:
# untested
csvw = csv.writer(sys.stdout)
for city, coords in cities.items():
weather = ForecastIO.ForecastIO(
api_key, latitude=coords[0], longitude=coords[1]
)
daily = FIODaily.FIODaily(weather)
row = [city]
for day in range(2, 7):
day_data = daily.get_day(day)
row.append(day_data['temperatureMin'])
row.append(day_data['temperatureMax'])
csvw.writerow(row)
More information about the Tutor
mailing list