Find number of columns in csv file

后端 未结 5 984
无人及你
无人及你 2021-02-02 08:53

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

5条回答
  •  日久生厌
    2021-02-02 09:13

    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

提交回复
热议问题