Tuesday, March 15, 2011

Why csv.reader is not pythonic?

I started to use the csv.reader in Python 2.6 but you can't use len on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.

Or is this just an abandoned module in later versions?

From stackoverflow
  • I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.

    import csv
    r = csv.reader(...)
    lines = [line for line in r]
    print len(lines) #number of lines
    for odd in r[1::2]: print odd # print ever other line
    
    Joan Venge : Thanks, I didn't know it was an iterator. I thought it was a multi dimensional list.
    saffsd : You can replace lines = [line for line in r] with lines = list(r)

0 comments:

Post a Comment