简体   繁体   中英

Python - get number of columns from csv file

I'm trying to determine the number of columns that are present in a CSV file in python v2.6. This has to be in general, as in, for any input that I pass, I should be able to obtain the number of columns in the file.

Sample input file: love hurt hit

Other input files: car speed beforeTune afterTune repair

So far, what I have tried to do is read the file (with lots of rows), get the first row, and then count the number of words in the first row. Delimiter is , . I ran into a problem when I try to split headings based on the sample input, and next len(headings) gives me 14 which is wrong as it should give me 3. Any ideas? I am a beginner.

with open(filename1, 'r') as f1:

 csvlines = csv.reader(f1, delimiter=',')

 for lineNum, line in enumerate(csvlines):
      if lineNum == 0:
           #colCount = getColCount(line)
           headings = ','.join(line)           # gives me  `love, hurt, hit`
           print len(headings)                 # gives me 14; I need 3
      else:
           a.append(line[0])
           b.append(line[1])
           c.append(line[2])

len("love, hurt, hit") is 14 because it's a string.

The len you want is of line , which is a list :

print len(line)

This outputs the number of columns , rather than the number of characters

#  old school

import csv

c=0
field={}

with open('csvmsdos.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        field[c]=row
        print(field[c])
        c=c+1

row=len (field[0])
column=len(field)

csvFile.close()

A simple solution:

with open(filename1) as file:
    # for each row in a given file
    for row in file:
        # split that row into list elements
        # using comma (",") as a separator,
        # count the elements and print
        print(len(row.split(",")))
        # break out of the loop after
        # first iteration
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM