In this python file program, we will read a random line from a file. Let’s consider we have readcontent.txt file with the below content. We will read a random line from a file with the help of the below-given steps.
# ReadContent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Steps to solve the program
- Import re library.
- Open the file, read it, and split the lines using open(‘readcontnent.txt’).read().splitlines().
- Read a random line from the lines using random.choice(lines).
- Print the output.
# Import random library
import random
# Read data from the file and splitting it into lines
lines = open('readcontent.txt').read().splitlines()
# Get a random line from the lines
data=random.choice(lines)
# Print output
print(data)
Output :
Line7 : This is Germany.