w3resource logo

:

Python Exercises

Python File I/O: Read a random line from a file

Python File I/O: Exercise-15 with Solution

Write a Python program to read a random line from a file.

Sample Solution:-

Python Code:

import random
def random_line(fname):
    lines = open(fname).read().splitlines()
    return random.choice(lines)
print(random_line('test.txt'))

Sample Output:

Append this text.

Python Code Editor:

Improve this sample solution and post your code through Disqus