Print random line from txt file?
<p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p>

<blockquote>
  <p>list index out of range</p>
</blockquote>

<p>Here's what I tried:</p>

<pre><code>f = open(filename. txt)
lines = f.readlines() 

rand_line = random. randint(1,10)
print lines[rand_line]
</code></pre>

<p>This code is correct, assuming that you meant to pass a string to <code>open</code> function, and that you have no space after the dot...
However, be careful to the indexing in Python, namely it starts at 0 and not 1, and then ends at <code>len(your_list)-1</code>.</p>

<p>Using <code>random.choice</code> is better, but if you want to follow your idea it would rather be:</p>

<pre><code>import random
with open('name.txt') as f:
    lines = f.readlines()
    random_int = random.randint(0,len(lines)-1)
    print lines[random_int]
</code></pre>

<p>Since <code>randint</code> includes both boundary, you must look until <code>len(lines)-1</code>.</p>

python random