Nardrek
Nardrek

Reputation: 477

Python how can change my open "mode" options for "open". R+A maybe?

I would like to change my code to do the same result. How can I do the same but in a different way ?

Just the open interrest me.

i mean the "f = open..... to the end.

here my code :

#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

def get_information(url):
  try:
    wunder_url_obj = urllib2.urlopen(url)
  except:
    print 'Could not open URL'
    return None

  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']
    date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " +     str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
    now = datetime.now()    
    header = "Datetime,current condition,Temperature,\n" 

    with open('out.csv', 'a') as f:
    if f.tell() == 0:
      f.write(header)

    f.write(','.join([date, str(temp_f), weather]))
    f.write('\n')
    f.close()

get_information('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')

here my editor :

enter image description here

Upvotes: 0

Views: 526

Answers (1)

falsetru
falsetru

Reputation: 369124

You can rewrite open ... close part as follow:

with open('out.csv', 'a') as f:
    f.seek(0, 2) # os.SEEK_END, on Windows file position set to 0 even in append mode.
    if f.tell() == 0:
        f.write(header)
    f.write(','.join([date, str(temp_f), weather]))
    f.write('\n')

file.tell() returns current file position.

Upvotes: 2

Related Questions