![](/img/trans.png)
[英]IndexError : list index out of range when retrieving text from a file
[英]IndexError: list index out of range in text file (Python)
我的这段代码位于永久的while循环内,每当我尝试从文本文件中获取随机行时,它有时都会引发索引错误。 有人可以帮我吗? 我已经检查了我的文本文件,里面有452行。 起初我以为这是一些数字错误,所以我减小了上限,但错误不断发生。 出现星号的代码是导致错误的原因。
if len(bank)==445:
bank = []
randinte = random.randint(1,450)
samecheck(randinte, bank, 450)
text_file = open("text.txt", "r")
**line = text_file.readlines()[randinte]**
twitter.update_status(
status=line)
text_file.close()
bank.append(randinte)
编辑:谢谢您的所有帮助! 这是我最终使用并工作的代码。 repopulate()是一种从1-451开始顺序填充库的方法。
if len(bank)==5:
bank = []
repopulate()
random.shuffle(bank)
text_file = open("text.txt", "r")
lines = text_file.readlines()
line = lines[bank.pop()]
twitter.update_status(
status=line)
text_file.close()
在看不到文本文件的情况下不清楚为什么会出现这些索引错误,但是最好还是避免对文件长度之类的东西进行硬编码。 另一种选择是使用random
模块中的choice
方法来选择从readlines()
返回的随机行,如下所示:
if len(bank)==445:
bank = []
text_file = open("text.txt", "r")
lines = text_file.readlines()
line = random.choice(lines) # choose a random line
twitter.update_status(
status=line)
text_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.