Python print random line from file without repeat
from random import sample
file_name = "text_database.txt"
lines = open(file_name, "r").read().splitlines()
for line in sample(lines, k=len(lines)):
print(line)
I use .read().splitlines()
instead of .readlines()
to purge the trailing whitespace (newlines) from each line. I could have also done:
lines = [line.rstrip("\n") for line in open(file_name, "r")]
Here is a description of random.sample
from the documentation:
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Alternatively, you could have shuffled your list of lines, and then iterated over them.
EDIT - I think I understand now. How's this?
def main():
from random import shuffle
file_name = "text_database.txt"
lines = open(file_name, "r").read().splitlines()
shuffle(lines)
sentinel = object()
def command_random():
try:
line = lines.pop()
except IndexError:
print("There are no more lines in the file!")
else:
print(line)
def command_quit():
nonlocal sentinel
sentinel = None
commands = {
"random": command_random,
"quit": command_quit
}
while sentinel is not None:
user_input = input("Please enter a command: ")
command = commands.get(user_input)
if command is None:
continue
command()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
this is a REALLY messy solution but i have tested this beforehand
f = open(text_database, "r")
list = []
list_of_nums = []
for i in f:
list.append(i)
elif command == '/random':
randomNum = random.randint(0, len(list) - 1)
def reRun():
global randomNum
for i in list_of_nums:
if randomNum == i:
randomNum = random.randint(0, len(list) - 1)
reRun()
reRun()
list_of_nums.append(randomNum)
print(list[randomNum])
What this code deos is go throgh all the lines in f and put them in a list. than it choses a random number bettween 0 and the lenght of the list and prints a random line corresponding to that number
Hope this helps! And welcome to stack overflow
elif command == '/random':
with open (text_database) as f:
lines = f.readlines()
while len(lines)>0:
max_int = len(lines)-1 #update the len each loop as we remove one each time
print(lines.pop(random.randint(0, max_int))) #pop a random value from the list