I/O Reading from a file
I'm using cod开发者_运维百科e 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?
f = open('boo.txt')
lines = [line for line in f]
f.close()
import random
selectedline = random.choice(lines)
print (selectedline)
Another way with use of context managers:
import random
with open("boo.txt", "r") as f:
print random.choice(f.readlines())
f = open('boo.txt')
import random
print random.choice(f.readlines())
精彩评论