我有一個非常大的 txt 檔案。我想通讀檔案的每一行并根據檔案(串列)的第三個元素獲取輸入。
因此,我將文本檔案轉換為串列并遍歷串列的每個元素以獲得我想要的輸出。
這是我的 txt 檔案的一部分:
34566---There was no file in there---Mr. [email protected]
36122---I found the file in [email protected]
64322
28890---I went to see the crowd---Henry [email protected]
44533---The weather made it perfect---Merry [email protected]
這是我使用的代碼:
value = input("Enter your name:")
filename = open("test.txt", "r")
for line in filename:
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
唯一的問題是中間的值不像串列中的其他元素那樣表現。所以,它給出了一個錯誤
IndexError: list index out of range
我不知道如何撰寫代碼來忽略與串列中其他元素不同的中間元素。請幫我。
uj5u.com熱心網友回復:
你可以試試這個
value = input("Enter your name:")
filename = open("anotherSix.txt", "r")
for line in filename:
if line == '\n':
continue
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
如您所見,我只添加了if line == '\n': continue基本上跳過空行的部分
uj5u.com熱心網友回復:
將您的條件更改為:
if len(line_num) > 2 and line_num [2] == value:
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465614.html
上一篇:從列的子集中采樣一行
