简体   繁体   中英

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

So I have a CSV file with up to 10 entries per line. (Up to 10 because most of the lines do not contain entries 9 and 10) And I need to find the fourth, sixth and eigth entries of each line.

Here is my code:

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)

Now this will find the correct values in the first line of the CSV file, but after this it will give an error

Error message:

 Line 7, in <module> b = line[3]
 IndexError: list index out of range

Would somebody tell me where I am going wrong?

[![Here is the first line of my CSV file][1]][1]

[1]: https://i.stack.imgur.com/osbBT.png

And here are my results

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

Edit: from csv sample you supplied, there is no commas, so use

a = line.split() instead of a = line.split(",")

try this with replacing 'line' by 'i':

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)

How the lines are formatted is not clear from you question but i'm assuming each line looks like following:

1,2,3,4,5,6,7,8,9,0

In that case, the following code should do it:

with open ('stats.csv', 'r') as f:
    for line in f:
        a = line.strip().split(",")
        print(a[3], a[5], a[7])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM