how can I get and print a random line from a txt file?

Question:

user = (random.choice("user.txt","r"))

how can I get and print a random line from a txt file?

Asked By: kuuk

||

Answers:

This code will print random line from the text file .

import pandas as pd
import random

df = pd.read_csv('salman.txt')
data = df.to_string()
data = data.split("n")
num1 = random.randint(0, len(data)-1)

print(data[num1])
Answered By: Salman Ahmed
import random

f = open("your_file.txt","r")
file_content = f.read().split('n') #split by using end line
f.close()

print(random.choice(file_content)
Answered By: Thisal

First read to list and then print random elemnts using random choice.

import random    
with open(r"user.txt") as file:
        lines = [line.rstrip() for line in file] ##['line1', Line2'...'Line n']
print(random.choice(lines))
Answered By: Bhargav
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.