Python @ DjangoSpin

PyPro #35 Picking a random line from a file

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Picking a random line from a file in Python

Picking a random line from a file in Python

Picking a random line from a file: Write Python code to pick a line randomly from a file.

Picking a random line from a file

# contents of wordOfTheDay.txt
pejorative: expressing contempt or disapproval.
broach: to bring up (a subject) for discussion or debate
frisson: a sudden, passing sensation of excitement
veracity: conformity to facts
infinitesimal: taking on values arbitrarily close to but greater than zero
augury: a sign of something coming
convivial: Friendly
abstruse: difficult to understand
derogate: to cause to seem inferior
whorl: A form that coils or spirals

from random import choice

fHOne = open('wordOfTheDay.txt')

content = fHOne.read()
lines = content.splitlines()

print(choice(lines))                  # prints randomly chosen line

fHOne.close()
Try it here.

See also:


Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon