使用 Python 计算文本文件中的列数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16448912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting number of columns in text file with Python
提问by Gabriel
I have two text files composed of spaced-separated columns. These are excerpts of these two files:
我有两个由间隔分隔的列组成的文本文件。这些是这两个文件的摘录:
FileA
文件A
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
文件B
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:
如您所见,FileA 有 7 列,FileB 有 8 列。这是我用来计算列数的代码:
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?
这个小代码正确地给出了 FileA (7) 的列数,而不是 FileB(也给出了 7)这是怎么回事,我该如何解决?
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)?
如果我计算的是行数而不是列数,那么: 1- 我如何计算列数?和 2- 鉴于我的实际文件有数千行/行,为什么我会得到这些结果 (7)?
采纳答案by Eric
import csv
with open('filename') as f:
reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
first_row = next(reader)
num_cols = len(first_row)
回答by Alfe
Read just the first line, use split to find all non-whitespace parts, count those:
只阅读第一行,使用 split 查找所有非空白部分,计算那些:
with file("bla") as f:
line = f.readline()
print len(line.split()), "columns"
回答by Ryan Saxe
just get the length of the first row!!
只需获取第一行的长度!!
import csv
file = 'my_File.csv'
reader = csv.reader(open(file,'rb'),delimiter=" ")
num_cols = len(next(read))

