繁体   English   中英

获取:尝试读取文本文件时出现索引超出列表错误

[英]Getting: index out of list error when trying to read text file

我正在尝试使用 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 作为每一行的开头

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

这会做: [l for l in file.readlines() if l.strip()]


file=open("text.txt","r")
file1 = [l for l in file.readlines() if l.strip()] #< --- Here


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

file.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))

Number of lines read                : 3
Number of samples read from the file: 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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