Reputation: 2889
I'm using code like this:
f = open('boo.txt')
line = f.readline()
print line
f.close()
How can I make it read a different line or a random line every time I open the script, instead of just printing out the first line?
Upvotes: 1
Views: 140
Reputation: 6953
Another way with use of context managers:
import random
with open("boo.txt", "r") as f:
print random.choice(f.readlines())
Upvotes: 6
Reputation: 35983
f = open('boo.txt')
lines = [line for line in f]
f.close()
import random
selectedline = random.choice(lines)
print (selectedline)
Upvotes: 6
Reputation: 30228
f = open('boo.txt')
import random
print random.choice(f.readlines())
Upvotes: 2