[英]Python - Having trouble with IndexError: list index out of range
預先感謝您的回答。 我試圖研究我自己對這個問題的答案數小時但無濟於事。 我現在正在尋求建議而不是答案,因為這是大學的作業問題。
我有一個程序將一組數據存儲在單行記錄中。 這保存在名為“sales.txt”的文件中
有一個變量 (customerIDInput) 從另一個函數帶來,它基本上是客戶 ID。
我的程序應該逐行搜索記錄,找到索引 0 中具有“customerIDInput”的每條記錄。
我在假設是循環的最后一次重復時遇到錯誤。 索引超出范圍。 我最初認為這是最后一個 (\\n),因此根本沒有任何索引......但是我已經放入了一個 rstrip(\\n') 並且問題沒有解決。
我意識到我是 python 的新手,答案可能很簡單,但是我想我已經無法理解了,似乎是時候在這里問你們聰明的人了:)
附件是我遇到困難的功能。
def searchFile ():
sales = open('sales.txt', 'r')
transaction = 'START'
while transaction != ' ':
transaction = sales.readline()
transactionStrip = transaction.rstrip('\n')
transaction_list = transactionStrip.split()
if transaction_list[0] == str(customerIDInput):
customerEntry = transaction_list
print('matching records are: ',customerEntry)
sales.close()
當您到達文件末尾時,文件對象上的readline
方法將返回一個空字符串。 當你split
空字符串時,你會得到一個空列表,它沒有第一個元素。 這就是transaction_list[0]
在文件末尾給你一個IndexError
的原因。
有幾種不同的方法可以解決此問題。 保持接近當前代碼,您可以調整while
循環的條件以查找transaction
為空字符串(而不是具有單個空格的字符串)並提前閱讀一行:
transaction = sales.readline() # read first line
while transaction != "":
# do stuff with non-empty transaction line
transaction = sales.readline() # read next line
然而,迭代文件中的行的更自然的方法是直接在文件對象上簡單地使用for
循環:
for transaction in sales:
# do stuff
以這種方式迭代將在文件末尾自動停止。
在實際嘗試獲取transaction_list[0]
以避免IndexError
之前,您可以通過調用if transaction_list:
(檢查其中是否有任何項目)來簡單地檢查此類索引是否存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.