-1 returns second to last item in python list -
i using python 3.4 write script pull data yahoo finance's chartapi page using urllib pull data , store in text file , numpy unpack it. however, when ever try access last element in list using [-1] end second last element instead of last element.
here relevant code:
import urllib.request import numpy np def n_year_data(symbol): tempfile = 'temp.txt' open(tempfile,'w+') # clear previous content yahoochartapi = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+symbol+'/chartdata;type=quote;range=1y/csv' urllib.request.urlopen(yahoochartapi) f: sourcecode = f.read().decode('utf-8') splitsource = sourcecode.split('\n') eachline in splitsource: splitline = eachline.split(',') if len(splitline) == 6: if 'values' not in eachline: savefile = open(tempfile,'a') linetowrite = eachline+'\n' savefile.write(linetowrite) date, close, high, low, openprice, volume = np.loadtxt(tempfile, delimiter=',', unpack=true) print(date[-1]) n_year_data("goog")
the code above should return last date, 20150707. returns 20150706 date before last date. furthermore when @ text file, dates there , should be. in advance help, or advice.
since you not correctly closing file after finish writing, might end having problem, or other potential problems.
don't open , append file in loop.
consider using this, instead:
with open('temp.txt', 'w') f: item in iterable: f.write('hello') open('temp.txt', 'r') f: line in f: print(line)
Comments
Post a Comment