0

我想将我的代码结果导出到 csv 文件(exel)中并在其中打印,但要注意标题行。

现在它在不考虑行的情况下像 exel 中的普通文本一样打印。

喜欢 :

外卖

我想要这样:

我想要的是

任何想法使它成为可能?

谢谢

#Source : http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples
import urllib2
import json
import time
import csv
from datetime import datetime#set the time



f =       urllib2.urlopen('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')

now = datetime.now()
current_year = now.year
current_day = now.day
current_month = now.month
current_hour = now.hour
current_minute = now.minute
current_second = now.second

json_string = f.read()
parsed_json = json.loads(json_string)
locations = parsed_json.get('locations', 'Beijing')
temp_f = parsed_json['current_observation']['temp_f']
weather = parsed_json['current_observation']['weather']

#--- Open the file   + write on it ---

f = open('out.csv','a') 
header = "location,temperature,weather,date\n" 
date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
f.write(header)
f.write(','.join([locations,str(temp_f),weather,date]))
f.write('\n')
f.close()
# --- And Close the file ---

在赛斯的大力帮助下

它打印这个:

在此处输入图像描述

4

1 回答 1

1

尝试类似的东西

header = "location\ttemperature\tweather\date\n"
f.write(header)
for i in xrange(len(weather)):
    f.write('\t'.join([locations[i],temp_f[i],weather[i],str(now.day)]))
    f.write('\n')
f.close()

或者没有循环的等价物for,如果你在你正在解析的循环内编写。

编辑:或更明确地:

f = open('out.csv','a') #open in append mode if you're already written some of the file.
header = "location\ttemperature\tweather\date\n" #only write this if you haven't already.
date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
f.write(header)
f.write('\t'.join([locations,temp_f,weather,date]))
f.write('\n')
f.close()
于 2013-07-17T05:45:51.893 回答