[英]Python - get number of columns from csv file
我正在尝试确定 python v2.6 中 CSV 文件中存在的列数。 这必须是一般的,因为对于我传递的任何输入,我应该能够获得文件中的列数。
示例输入文件: love hurt hit
其他输入文件: car speed beforeTune afterTune repair
到目前为止,我尝试做的是读取文件(有很多行),获取第一行,然后计算第一行中的单词数。 分隔符是,
。 当我尝试根据示例输入拆分headings
时遇到了问题,下一个len(headings)
给了我14
,这是错误的,因为它应该给我 3。有什么想法吗? 我是初学者。
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")
是14,因为它是一个字符串。
你想要的len
是line
,它是一个list
:
print len(line)
这将输出列数,而不是字符数
# 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()
一个简单的解决方案:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.