Search code examples
pythonrandomprintingwords

Randomly generate a line from a .txt file


I'm rather new to python and have been set an assignment. I need to randomly generate a word from a .txt file. I can retrieve specific lines, such a get line 2, or line 5, however I want to randomly generate what line is retrieved.

This is what I currently have

input("Press Enter to continue...")

with open('words.txt') as f:
    for i, line in enumerate(f, 1):
        if i == 1:
         break
print (line)

I tried doing this but it just came up with randrange is not defined

input("Press Enter to continue...")

import random
with open('words.txt') as f:
    for i, line in enumerate(f, randrange(1,14)):
        if i == 1:
         break
print (line)

Solution

  • To select one line at random from a file:

    import random
    with open('/etc/passwd') as f:
        print (random.choice(list(f)))
    

    To select an arbitrary line from a file, say the i-th line:

    with open('/etc/passwd') as f:
        print (list(f)[i])
    

    Or, this might be more efficient:

    import itertools
    with open('/etc/passwd') as f:
        print (next(itertools.islice(f, i, i+1)))
    

    However, the "simplest, and almost certainly most efficient, way to select an arbitrary line from a file is linecache.getline('/etc/password', i)." – abarnert