简体   繁体   中英

Python3 - list index out of range - extracting data from file

I want to extract data from a file and change the value of an entry with a 'for-loop'.

f = open(r"C:\Users\Measurement\LOGGNSS.txt", "r")
x=0
content = [[],[]]
for line in f:
    actualline = line.strip()
    content.append(actualline.split(","))
    x+=1
f.close

print(x)
for z in range(x):
    print(z)
    print(content[z][1])

IndexError: list index out of range

Using a real value instead of the variable 'z' works fine. But I need to change all first entries in the whole 2D-Array. Why it does not work?

你用两个空数组初始化你的内容,所以这两个都找不到第一个索引( [1] ),只需用一个空数组初始化它

content = []

Your code has several problems. First of all, use the with statement to open/close files correctly. Then, you don't need to use a variable like x to keep track of the number of lines, just use enumerate() instead!

Here is how I would refactor your code to make it slimmer and more readable.

input_file = r"C:\Users\Measurement\LOGGNSS.txt"
content = []

with open(input_file, 'r') as f:
    for line in f:
        clean_line = line.strip().split(",")
        content.append(clean_line)

for z, data in enumerate(content):
    print(z,'\n',data)

Note that you could print the content while reading the file in one single loop.

with open(input_file, 'r') as f:
    for z, line in enumerate(f):
        clean_line = line.strip().split(",")
        content.append(clean_line)
        print(z,'\n', clean_line)

Finally, if you are dealing with a plain and simple csv file, then use the csv module from the standard library.

import csv

with open(input_file, 'r') as f:
    content = csv.reader(f, delimiter=',')

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