按列(标题)和行打印python中CSV的行

按列(标题)和行打印python中CSV的行,python,csv,Python,Csv,我想将我的代码结果导出到一个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

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

它打印了以下内容:

试试类似的方法

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()

这可能是因为您的
位置
温度
天气
str(now.day)
不是这些属性的列表,而是每个位置的单个属性。尝试删除循环和索引的
,然后应该可以工作。没关系,每个人都是新的。现在不应该有for循环,请检查我编辑的答案。你能用给出错误的新代码编辑你的问题吗?而且,更好的是,打印
位置
温度
天气
,以及
日期
,这样我们就可以准确地看到它们是什么。我明白了,将
温度
更改为
str(温度)
excel中应该有一个选项使用tab作为分隔符,如果找不到它,请尝试将“我的代码”中的所有
'\t'
s更改为
',
s,逗号可能是excel的本机分隔符。