0

我想知道如何避免我的脚本中的 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')

在我的编辑器中我也试过这个;

在此处输入图像描述

4

1 回答 1

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)

这里重要的是要注意我们正在以常规顺序访问文件写入 - 一次写入标题,然后顺序写入信息。也许更好的方法是做类似的事情

 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 回答