开发者

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())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜