每次运行脚本时,Python 头都会打印一次,而不是每次

标签 python csv header export-to-csv

我希望我的标题仅在脚本每小时运行一次时打印一次(我将使用窗口计划,因此不要关注计划)以在旧数据下收集新数据。

我的实际打印:

actual

我希望它是这样的:

enter image description here

这是我的代码(谁工作)

有什么想法吗?

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

最佳答案

我对之前的版本深表歉意。我遗漏了一个小细节,但我现在已经修复了。正确的代码如下:

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

关于每次运行脚本时,Python 头都会打印一次,而不是每次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17693972/

相关文章:

python - 文本框不随包含框架扩展 - TKinter

python - 带有破折号的文件名的代码分析不完整

python - 重命名未命名的列 Pandas 数据框

powershell - 重定向到 null 是在 PowerShell 脚本中丢弃行的正确方法吗?

c - 在c中读取JPEG头文件

WPF DataGrid - 我可以用属性装饰我的 POCO 以具有自定义列名吗?

header - Varnish - 生成 http header 溢出

python - 如何使用 matplotlib 绘制多元线性回归模型

python - 尝试理解 Python 中的可选参数、列表参数和命名参数

c++ - 如何使用没有明确格式样式的 C++ 解析 CSV 文件