![](/img/trans.png)
[英]Why do I get "IndexError: list index out of range" in my Python code Cows and Bulls?
[英]Why did my Python code get the IndexError: list index out of range
當我運行代碼時,我遇到了以下錯誤:
IndexError:列表索引超出范圍
我的代碼有什么問題?
fin = open('words.txt')
for line in fin:
word = line.strip()
if len(word) > 20:
print(word)
print(fin.readlines()[1]) #It is in this line that the error report shows
您正在嘗試獲取readlines
方法執行結果的第二個元素(從零開始)。 默認情況下這是不安全的,因為文件只能包含一個字符串。 但是在這種特殊情況下,無論打開的文件中的行數如何,您都會在fin.readlines()
收到空列表,因為您已經閱讀了上面for line in fin
循環中使用for line in fin
)。 您不能只閱讀兩次並需要尋找開頭或重新打開文件:
~ echo 1 >> t.txt
~ echo 2 >> t.txt
~ echo 3 >> t.txt
~ python3
二次閱讀內容:
>>> with open('t.txt') as f:
... f.readlines()
... f.readlines()
...
['1\n', '2\n', '3\n']
[]
尋求開始:
>>> with open('t.txt') as f:
... f.readlines()
... f.seek(0)
... f.readlines()
...
['1\n', '2\n', '3\n']
0
['1\n', '2\n', '3\n']
這是因為循環結束后讀取的文件已經結束。 使用seek
,您可以再次將指針設置到開頭。
fin = open('text_file.txt')
for line in fin:
word = line.strip()
if len(word) > 20:
print(word)
fin.seek(0, 0)
print(fin.readlines()[1])
這是它的鏈接https://python-reference.readthedocs.io/en/latest/docs/file/seek.html
目前還不清楚你到底想做什么? 但錯誤應該消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.