Find number of columns in csv file

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

    I would rebuild it as follows ( if the file is not too big ):

    import csv
    f = 'testfile.csv'
    d = '\t'
    
    reader = list(csv.reader(f,delimiter=d))
    fields = len( reader[0] )
    for row in reader:
        if fields == 1:
            pass
        elif fields == 2:
            pass
        elif fields == 3:
            pass
        else:
            raise CSVError("Too many columns in input file.")
    

提交回复
热议问题