SourD
SourD

Reputation: 2889

I/O Reading from a file

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

Answers (3)

andreypopp
andreypopp

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

phimuemue
phimuemue

Reputation: 35983

f = open('boo.txt')
lines = [line for line in f]
f.close()
import random
selectedline = random.choice(lines)
print (selectedline)

Upvotes: 6

unbeli
unbeli

Reputation: 30228

f = open('boo.txt')
import random
print random.choice(f.readlines())

Upvotes: 2

Related Questions