How to put random lines from a file into a string in python?
Question: what i want to do is write a code that has a file (in the code, no need to be
input by user), and the code picks a random line from the file - whatever it
is, a long line, an ip or even a word and at the end of the loop puts it into
a string so i could use that in other parts of the code.

i tried using `randomchoice(lines)` but wasn't sure how to continue from here.
after that i tried using:

    
    
    import random
    def random_line(afile):
        line = next(afile)
        for num, aline in enumerate(afile):
          if random.randrange(num + 2): continue
          line = aline
        return line
    

which also for some reason didnt work for me.


Answer: The last method you posted worked for me. Maybe you are not opening the file
correctly. Here is another approach, using `random.choice`

    
    
    import random
    
    def random_line(f):
        return random.choice([line for line in f])
    
    f = open("sample.txt", 'r')
    
    print random_line(f)
    

**Edit:**

Another way would be (thanks to @zhangxaochen):

    
    
    def random_line(f):
        return random.choice(f.readlines())
    

