gpt4 book ai didi

Python - 从 csv 文件中获取列数

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:09 31 4
gpt4 key购买 nike

我正在尝试确定 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 因为它是一个字符串。

你要的lenline,也就是list:

print len(line)

这会输出列数,而不是字符数

关于Python - 从 csv 文件中获取列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21790078/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com