我想知道如何避免我的脚本中的 URL 错误。并且想知道在运行文件时只打开一次文件(而不是像我的代码中的两次)而不产生错误的方式。(实际代码工作)
帮助可能在这里:
http://docs.python.org/2/library/urllib2.html#urllib2.URLError
用“尝试”和“例外”?
你能就此提出建议,而不是这对我的代码有效吗?
对于错误 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
try:
wunder_url_obj = urllib2.urlopen('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')
except:
print 'Could not open URL'
exit()
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']
#--- Open the file + write on it ---
prev_data = open('out.csv', 'r').read()
# Add a header only if the file is empty
if prev_data == '':
with open('out.csv','a') as f:
header = "Datetime,current condition,Temperature,\n"
prev_data.write(header)
date = str(now.month) + "/" + str(now.day) + "/" + str(now.year) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
prev_data.write(','.join([date,weather,str(temp_f)]))
prev_data.write('\n')
在我的编辑器中我也试过这个;