1

古いデータの下で新しいデータを収集するために、スクリプトが毎時間実行されるときにヘッダーを1回だけ印刷したいと思います(そのためにウィンドウのスケジュールを使用するので、スケジュールに集中しないでください)。

私の実際のプリント:

実際

そして、私はそれが次のようになりたいです:

ここに画像の説明を入力

ここに私のコード(誰が働いているか)

何か案が ?

#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



f = urllib2.urlopen('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')

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 = f.read()
parsed_json = json.loads(json_string)
locations = parsed_json.get('locations', 'Beijing')
temp_f = parsed_json['current_observation']['temp_f']
weather = parsed_json['current_observation']['weather']

#--- Open the file   + write on it ---

f = open('out.csv','a')
header = "Datetime,Location,Temperature,current_condition\n"
date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " + str(now.hour)          + ":" + str(now.minute) + ":" + str(now.second)
f.write(header)
f.write(','.join([date,locations,str(temp_f),weather]))
f.write('\n')
f.close()
# --- And Close the file ---
4

2 に答える 2

2

以前のバージョンについて深くお詫び申し上げます。見落としていた部分がありましたが、修正しました。正しいコードは次のとおりです。

#--- Open the file   + write on it ---

f = open('out.csv','a')
prev_data = open('out.csv', 'r').read()

header = "Datetime,Location,Temperature,current_condition\n"

# Add a header only if the file is empty
if prev_data == '':
    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,locations,str(temp_f),weather]))
f.write('\n')
f.close()
# --- And Close the file ---
于 2013-07-17T07:55:08.807 に答える