Python 获取:尝试读取文本文件时出现索引列表外错误
我试图使用Python将数据集中的所有浮点元素提取到三列中。但是我得到了一个索引超出范围的错误Python 获取:尝试读取文本文件时出现索引列表外错误,python,Python,我试图使用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 t
#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
以zzzzz作为每行的开头,您的脚本可以很好地处理您提供的数据。问题很可能在输入文件中找到。如果文件中只有一行不符合数据格式(即少于6列,或者可能是空行),则其中一个
列[n]
语句会触发索引超出范围错误。这将执行:[l代表文件中的l.readlines()如果是l.strip()]
#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))
我无法重现这个错误。文本数据有问题。谢谢你帮我调查。我发布的数据只是输入文本文件中的几行。然而,我注意到文件中有空行,正如指出的那样,可能会导致错误。我是新来的网站,不知道如何上传相关文件。谢谢,是的,输入文件中有一些空行。关于如何使程序仅读取非空行的任何建议?一种可能性是,在使用columns=line.split()拆分行后,可以检查列列表的长度。如果len(columns)6和than相应地处理。非常感谢,这对我很有用。这段代码[l for l in file.readlines()if l.strip()]也会去掉输入文本文件中的所有空行。您是否有可用的语法,以便我能更深入地理解这里的参数?
l='\n';l、 strip()
如果你有这个新行,那么strip会给你'
如果没有(l='anystring'
)l.strip()
会给你'anystring'
基本上你是在过滤没有新行的行
Number of lines read : 3
Number of samples read from the file: 0