スクリプトで URL エラーを回避する方法を知りたいです。また、実行時にエラーを発生させずに、ファイルを 1 回だけ (私のコードのように 2 回ではなく) 開く方法を知りたいです。(実際のコード作業)
ヘルプはここにあります:
http://docs.python.org/2/library/urllib2.html#urllib2.URLError
「try」と「exept」で?
これが私のコードで機能するよりも、これについてアドバイスできますか?
エラーURLが間違っている場合にユーザーにメッセージを投稿したい場合:
たとえば、アドレスを変更します。
そして実行時:エラーが表示されるようになりました
だから「悪い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')
私のエディターでもこれを試しました。