Find number of columns in csv file

后端 未结 5 1044
无人及你
无人及你 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:23

    What happens if the user provides you with a CSV file with fewer columns? Are default values used instead?

    If so, why not extend the row with null values instead?

    reader = csv.reader(f,delimiter=d)
    for row in reader:
        row += [None] * (3 - len(row))
        try:
            foo, bar, baz = row
        except ValueError:
            # Too many values to unpack: too many columns in the CSV
            raise CSVError("Too many columns in input file.")
    

    Now bar and baz will at least be None and the exception handler will take care of any rows longer than 3 items.

提交回复
热议问题