所以我有一个CSV文件,每行最多10个条目。 (最多10条,因为大多数行不包含条目9和10)而且我需要找到每行的第四,第六和第八条条目。
这是我的代码:
ll = []
with open ('stats.csv', 'r') as f:
for line in f:
a = line.split(",")
ll.append(a)
for i in ll:
b = line[3]
c = line[5]
d = line[7]
print(b,c,d)
现在,这将在CSV文件的第一行中找到正确的值,但在此之后会出现错误
错误消息:
Line 7, in <module> b = line[3]
IndexError: list index out of range
有人会告诉我我要去哪里错吗?
[![Here is the first line of my CSV file][1]][1]
[1]: https://i.stack.imgur.com/osbBT.png
这是我的结果
0.010910065844655037 0.004127473570406437 0.9779554605484009
Traceback (most recent call last):
File "/*/*/*/read_xyz_stats.py", line 8, in <module>
b = i[3]
IndexError: list index out of range
答案 0 :(得分:1)
编辑:根据您提供的csv示例,没有逗号,因此请使用
a = line.split()
而不是a = line.split(",")
尝试用“ i”替换“ line”:
ll = []
with open ('stats.csv', 'r') as f:
for line in f:
a = line.split()
ll.append(a)
for i in ll:
b = i[3]
c = i[5]
d = i[7]
print(b,c,d)
答案 1 :(得分:1)
从您的问题尚不清楚行的格式如何,但我假设每一行都如下所示:
1,2,3,4,5,6,7,8,9,0
在这种情况下,应执行以下代码:
with open ('stats.csv', 'r') as f:
for line in f:
a = line.strip().split(",")
print(a[3], a[5], a[7])