[Tutor] Writing for loop output to csv
Cameron Simpson
cs at cskk.id.au
Thu Sep 6 18:17:33 EDT 2018
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
>
>the data prints out on top of each other like this:
>
>Nantou, Taiwan 29.49 20.79
>Nantou, Taiwan 30. 49 21.56
Normally there would be more commas in CSV output, eg:
Nantou, Taiwan,29.49,20.79
and because "Nantou, Taiwan" is a single string, it would typically look like
this:
"Nantou, Taiwan",29.49,20.79
to make that clear, otherwise the embedded comma would make it two CSV columns.
>Code I have:
>
>from forecastiopy import *
>import csv
I see you're importing the csv module, but not using it. [...]
[...snip...]
>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):
> print(str(city) + " " + str(daily.get_day(day)['temperatureMax']) +
>" " + str(daily.get_day(day)['temperatureMin']))
First a small suggestion. Change this:
print(str(city) + " " + str(daily.get_day(day)['temperatureMax']) + " " + str(daily.get_day(day)['temperatureMin']))
like this:
day_data = daily.get_day(day)
print(str(city) + " " + str(day_data['temperatureMax']) + " " + str(day_data['temperatureMin']))
It fetches the daily data just once and makes your subsequent code easily to
read and debug.
Second, your actual problem. Your loop is basicly sound, but you're using a
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']])
You'll also need to "import sys" up the top to use the name "sys.stdout".
See how now you're just passing a list of the values to the csv writer?
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list