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'))

Output :

lasith madushanka

Python Code Editor:

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

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number