Python's CSV reader

Christopher Subich spam.csubich+block at block.subich.spam.com
Thu Aug 4 06:47:23 CEST 2005


Stephan wrote:
> Can the CSV module be coerced to read two line formats at once or am I
> better off using read and split?

Well, readlines/split really isn't bad.  So long as the file fits 
comfortably in memory:

fi = open(file)
lines = fi.readlines()
evens = iter(lines[0::2])
odds = iter(lines[1::2])
csv1 = csv.reader(evens)
csv2 = csv.reader(odds)

The trick is that the "csvfile" in the CSV object doesn't have to be a 
real file, it just has to be an iterator that returns strings.  If the 
file's too big to fit in memory, you could piece together a pair of 
iterators that execute read() on the file appropriately.



More information about the Python-list mailing list