My program needs to read csv files which may have 1,2 or 3 columns, and it needs to modify its behaviour accordingly. Is there a simple way to check the number of columns withou
You can use itertools.tee
itertools.tee(iterable[, n=2])
Return n independent iterators from a single iterable.
eg.
reader1, reader2 = itertools.tee(csv.reader(f, delimiter=d))
columns = len(next(reader1))
del reader1
for row in reader2:
...
Note that it's important to delete the reference to reader1
when you are finished with it - otherwise tee
will have to store all the rows in memory in case you ever call next(reader1)
again