Find number of columns in csv file

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

    This seems to work as well:

    import csv
    
    datafilename = 'testfile.csv'
    d = '\t'
    f = open(datafilename,'r')
    
    reader = csv.reader(f,delimiter=d)
    ncol = len(next(reader)) # Read first line and count columns
    f.seek(0)              # go back to beginning of file
    for row in reader:
        pass #do stuff
    

提交回复
热议问题