我想将我的代码结果导出到 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 ---
在赛斯的大力帮助下
它打印这个: