0

スクリプトで 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')

私のエディターでもこれを試しました。

ここに画像の説明を入力

4

1 に答える 1

2

まず、変数名を異なるものにするようにします (2 つの異なる がありますf)。今のためにtry: except

try:
    wunder_url_obj = urllib2.urlopen(api_wunder_url_opath)
except:
    print 'Could not open URL'
    sys.exit()

私はあなたが悪い URL を開いたときに終了したいと思っていると仮定しています - しかし、それはあなた次第です。

既に開いているファイル ( out.csv) を開こうとしています。ファイルの読み取り/書き込みを整理してみてください-with物事をきれいでシンプルに保つためにステートメントを使用してみてください:

#--- 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"

        f.write(header)

        date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " + str(now.hour)       + ":" + str(now.minute) + ":" + str(now.second)
        f.write(','.join([date,weather,str(temp_f)]))
        f.write('\n')

# --- And Close the file ---

編集

コードを書き直すのではなく、問題を再考することをお勧めします。あなたはしたい

  1. URL から情報を読み取る
  2. その情報をファイルに書き込む
  3. 繰り返す(1へ)

ここで重要なことは、ファイルの書き込みに通常の順序でアクセスしていることに注意することです。1 回目はヘッダーを書き込み、次に順番に情報を書き込みます。たぶん、より良いアプローチは次のようなことをすることです

 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

    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'

したがって、この関数は何度も呼び出すことができ、毎回 csv ファイルの行を返します。次に、それを呼び出してファイルに書き込みます。

 with open(my_csv_file, 'w') as fo:

      fo.write(header)

      for i in range(10):  # or whatever time scale you have

           fo.write(get_information(my_url))
于 2013-07-18T08:10:57.873 に答える