How to get a random line from a text file in Python

This tutorial is about how to get a random line from a text file in Python. Python contains a lot of predefined modules. Python has a module that is the random module by using the random module to get a random line from the text file(.txt).

The following are constraints to get a random line:

  • The file path must be specified to open the file on the computer.
  • We must specify the mode of the file while the file is opening.

Importing Random Module:

So, let us have a look at importing the random module:

import random

Importing random module in .py file

Basic functions of files:

Before getting the data from the file you must open the file to get the data. After the end of the program, you must close the file.

Syntax to open a file:
  • open(path…,mode)

The open function contains two arguments :

  1. Path of the file you must add another backslash(\) to the path to get the file from the location.
  2. The mode must be specified to perform the actions on the file.
  3. They are three modes to open a file:
  • “r” mode: In this mode, you must able t0 read the file.
  • “w” mode: In this mode, you must able t0 write the file.
  • “a” mode: In this mode, you must able t0 append the data into the file.

By selecting the specific mode to open a file to perform the respective task on the file.

Syntax to close a file:
  • object.close()

By using object address the open file will be closed by using a close() function.

Text file (.txt):

Here the text file contains the following data:

hello hi
good morning
see you later
good night

Example to get a random line from .txt file in Python

The below program shows how to get a random line from the existing text file.

import random
s=open("C:\\Users\\sairajesh\\Desktop\\new.txt","r")
m=s.readlines()
l=[]
for i in range(0,len(m)-1):
    x=m[i]
    z=len(x)
    a=x[:z-1]
    l.append(a)
l.append(m[i+1])
o=random.choice(l)
print(o)
s.close()
    

output:

hello hi

Explanation:

  • We must specify the path of the file and mode of the file in open function.
  • It returns list type along with \n character by using slice operation remove the \n character presented in the list m append into the new list “l”.
  • By using the random.choice() method to select a line presented in the list and display the output.

Example 2:

import random
s=open("C:\\Users\\sairajesh\\Desktop\\new.txt","r")
m=s.readlines()
l=[]
for i in range(0,len(m)-1):
    x=m[i]
    z=len(x)
    a=x[:z-1]
    l.append(a)
l.append(m[i+1])
o=random.choice(l)
print(o)
s.close()
    

output:

good night

Explanation:

  • The same program run again you get another or same line because choice() method select different line or same line based on system logic

Also read:

Leave a Reply