簡體   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