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

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

kuuk
  • 5
  • 2

2 Answers2

0
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)
Thisal
  • 64
  • 4
0

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