Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of columns in text file with Python

I have two text files composed of spaced-separated columns. These are excerpts of these two files:

FileA

 1 1742.420   -0.410  20.1530   0.4190   1.7080   0.5940
 2 1872.060    0.070  21.4710   0.2950   0.0670   0.3380
 3 1918.150    0.150  18.9220   0.0490   1.4240   0.1150
 4 1265.760    0.170  19.0850   0.0720   1.3330   0.1450
 5  308.880    0.220  20.5020   0.1570   0.0200   0.1720
 ....

FileB

 1 1198.367    6.465  15.684 0.015  3.119 0.140  1
 2 1451.023    6.722  17.896 0.031  0.171 0.041  1
 3 1032.364    6.788  18.895 0.074 -0.084 0.088  1
 4  984.509    7.342  19.938 0.171  0.043 0.322  1
 5 1068.536    7.369  19.182 0.091  0.486 0.143  1
 ....

As you can see FileA has 7 columns and FileB has 8. This is the code I use to count the columns:

import csv
file = 'filename'
reader = csv.reader(file)
num_cols = 0
for col in reader:
    num_cols = num_cols + 1

This little code correctly gives the number of columns for FileA (7) but not for FileB (also gives 7) What's going on and how can I fix it?

If I'm counting rows instead of columns then: 1- how can I count the columns? and 2- given that my actual files have several thousands of lines/rows, why am I getting these results (7)?

like image 890
Gabriel Avatar asked May 08 '13 19:05

Gabriel


People also ask

How do you count the number of lines in a text file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do you count lines of code in Python?

Use os. walk to traverse the files and sub directories, use endswith to filter the files you want to count, open each file and use sum(1 for line in f) to count the lines, aggregate all the file line counts.

How do I count the number of lines in a text file?

wc command - The wc (word count) command is one of the easiest and fastest methods of getting the amount of characters, lines, and words in a file.


1 Answers

import csv

with open('filename') as f:
    reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
    first_row = next(reader)
    num_cols = len(first_row)
like image 84
Eric Avatar answered Sep 20 '22 21:09

Eric