簡體   English   中英

當數據始終處於特定順序但值不同時,如何在CSV文件中查找特定值

[英]How do I find specific values inside of a CSV file when the data is always in a certain order but with different values

所以我有一個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

編輯:從您提供的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,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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM