Nardrek
Nardrek

Reputation: 477

Python header print one time for every time I run the script not each time

I would like my header be print only one time when the script will run every hour (I will use schedule of windows for that so don't be focus on the schedule) to collect new data under the old data.

My actual print :

actual

and I would like it be like this :

enter image description here

Here my code (who work)

Any idea ?

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

Upvotes: 1

Views: 2140

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Just check if the file exists and create a new file with a header if it doesn't:

import os

if os.path.exists(my_csv_file_path):
    header_exists = True
else:
    header_exists = False

with open(my_csv_file_path, "a+"):
    if not header_exists:
        write_header()

    write_row()

Upvotes: 0

user2286078
user2286078

Reputation:

I thoroughly apologize for the previous versions. There was a tiny detail that I was missing but I've fixed it now. Here's the correct code:

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

Upvotes: 2

Related Questions