首页 > 解决方案 > 获取:尝试读取文本文件时出现索引超出列表错误

问题描述

我正在尝试使用 Python 将数据集中的所有浮点元素提取到三列中。但我得到一个索引超出范围错误。

#Reading the file line by line, separating each line by columns

file1=open("./Marine/bath.txt","r") 
x=[]                                  
y=[]
z=[]
i=1
for line in file1:   ### Reading sequencially the lines of the file1 object
    if i>4:
        columns=line.split()
        x.append(float(columns[3]))
        y.append(float(columns[1]))
        z.append(float(columns[5]))
    i=i+1

file1.close()

x=np.array(x)
y=np.array(y)
z=np.array(z)


print("Number of lines read                :",i-1)
print("Number of samples read from the file:",len(x))

数据如下所示:

zzzzzzz   50.0 ttttttt   329365.108 bbbbbbbb  4358562.104
zzzzzzz   220.00000000000003 ttttttt   402708.003 bbbbbbbb  4344547.635
zzzzzzz   110.00000000000001 ttttttt   347930.603 bbbbbbbb  4233132.610

以 zzzzzzz 作为每一行的开头

标签: python

解决方案


您的脚本适用于您提供的数据。问题很可能在输入文件中找到。如果文件中只有一行不符合数据格式(即少于 6 列,或者可能是空行),则其中一个columns[n]语句会触发索引超出范围错误。


推荐阅读