Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get number of columns from csv file

Tags:

python

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])
like image 565
Eagle Avatar asked Feb 14 '14 21:02

Eagle


People also ask

How do I find the number of rows and columns in a CSV file in Python?

To get the number of rows, and columns we can use len(df. axes[]) function in Python.

How many columns are in a CSV file?

csv files have a limit of 32,767 characters per cell. Excel has a limit of 1,048,576 rows and 16,384 columns per sheet. CSV files can hold many more rows. You can read more about these limits and others from this Microsoft support article here.

How do I see all columns in a CSV file in Python?

In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file.

How do you count elements in a CSV file in Python?

Using len() function Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file.


1 Answers

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

like image 81
mhlester Avatar answered Oct 03 '22 01:10

mhlester