Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object of type '_csv.reader' has no len(), csv data not recognized

Tags:

python

csv

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  ################
like image 361
Studix Avatar asked Jan 28 '17 11:01

Studix


2 Answers

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.

like image 103
Jean-François Fabre Avatar answered Sep 22 '22 11:09

Jean-François Fabre


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)
like image 33
Георгий Черноусов Avatar answered Sep 23 '22 11:09

Георгий Черноусов