我认为我的代码有问题,但命令提示符没有说有错误。
我为 open 写错了代码吗?我希望它从我输入的 url 中获取数据(所以我写得很好)并在旧数据下打印新数据而不创建新标题(因为我会每小时运行一次)。
这是我想要的结果。
这是我的代码:
#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
def get_information(url):
try:
wunder_url_obj = urllib2.urlopen('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')
except:
print 'Could not open URL'
return None
else:
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 = wunder_url_obj.read()
parsed_json = json.loads(json_string)
temp_f = parsed_json['current_observation']['temp_f']
weather = parsed_json['current_observation']['weather']
date = str(now.month) + "/" + str(now.day) + "/" + str(now.year) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
return ','.join([date, weather, str(temp_f)]) + '\n'
now = datetime.now()
header = "Datetime,current condition,Temperature,\n"
f = open('out.csv','a')
prev_data = open('out.csv', 'r').read()
# Add a header only if the file is empty
if prev_data == '':
f.write(header)
f.write(','.join([date,str(temp_f),weather]))
f.write('\n')
f.close()
在我的编辑器中: