擅长:python、mysql、java
<p>在<code>while</code>循环的每次迭代中,您都要覆盖<code>fortunes</code>。
在EOF处<a href="https://docs.python.org/2/library/stdtypes.html#file.readline" rel="nofollow">^{<cd3>}</a>返回一个空字符串,因此<code>fortunes[rand_line]</code>引发<code>IndexError</code>。您可以改用<a href="https://docs.python.org/2/library/stdtypes.html#file.readlines" rel="nofollow">^{<cd6>}</a>(或者将file对象用作迭代器):</p>
<pre><code>with open("fortunes.txt", "r") as fortunes_file:
fortunes = fortunes_file.readlines() # alternatively, use list(fortunes_file)
print(random.choice(fortunes))
</code></pre>