tags:

views:

90

answers:

3
f = open('boo.txt')
line = f.readline()
print line
f.close()

How can I make it read a different line or a random line everytime I open the script, instead of just printing out the first line eveytime.

+6  A: 
f = open('boo.txt')
lines = [line for line in f]
f.close()
import random
selectedline = random.choice(lines)
print (selectedline)
phimuemue
You can replace last line with more elegant `selectedline = random.choice(lines)`
nailxx
Awesome, thanks.
phimuemue
Great, simple answer!
Wez
Thank you for your help
SourD
+2  A: 
f = open('boo.txt')
import random
print random.choice(f.readlines())
unbeli
It is better to close file after.
andreypopp
+5  A: 

Another way with use of context managers:

import random

with open("boo.txt", "r") as f:
    print random.choice(f.readlines()) 
andreypopp