Python file program to read a random line from a file

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
  1. Import re library.
  2. Open the file, read it, and split the lines using open(‘readcontnent.txt’).read().splitlines().
  3. Read a random line from the lines using random.choice(lines).
  4. 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.

 

 

get the count of a specific word in a file.

copy the file’s contents to another file after converting it to lowercase.

Leave a Comment