我想将我的代码的结果导出到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 ---
在seth的大力帮助之后
打印出来:
答案 0 :(得分: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()