The following is a self-contained example. Change the "folder_name" to run it. This answers :
reader type = _csv.reader
list(reader) = []
_csv.reader' has no len()
I have tried many things but still cannot access the data, though it is in the file. Any help will be very welcome. Bern
################ INPUTS ################
folder_name = '/Users/Shared/TS1/Historiques Dividendes/'
path_to_inter_file = folder_name + 'interm.csv'
################ End INPUTS ################
################ MAIN ################
## --- Creates "inter" file after removing previous one if existed
if os.access(path_to_inter_file, os.W_OK) == True:
os.remove(path_to_inter_file)
if os.access(path_to_inter_file, os.W_OK) == False:
finter = open(path_to_inter_file,'w')
## --- Gets data from an URL
URL = "<http://chart.finance.yahoo.com/table.csv?s=XLB&a=0&b=24&c=1980&d=0&e=24&f=2040&g=v&ignore=.csv'>"
data = requests.get(URL)
## --- Loads data into "inter" file
finter.write(data.text)
finter.close
## --- Reopens "inter" file to read data
finter = open(path_to_inter_file,'r')
mreader = csv.reader(finter,delimiter=',')
print type(mreader)
list(mreader)
print list(mreader)
len(mreader)
## --- Closes "inter" file and removes it
finter.close()
os.remove(path_to_inter_file)
################ End MAIN ################
mreader
is an iterator. It has no len.
But you're consuming it to a list the line before, so you could just do:
mreader = list(mreader)
to convert the iterator into an actual list of rows, which now has a len
Aside: finter.close
does nothing. Use finter.close()
or a with
context block to handle that automatically.
Taking list from mreader
is memory expensive operation.
I'd prefer simply doing this:
c = 0
with open(path_to_inter_file, 'r') as f:
reader = csv.reader(f, delimiter=';')
for i, row in enumerate(reader):
c += 1
print(c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With