samedi 14 septembre 2019

Python print random line from file without repeat

I have a little program which prints random lines from a text file. I want to save the the already chosen lines in a list or something else, so it don't will repeat next time.

Example

text_database.txt

  1. This is a line
  2. This is an other line
  3. This is a test line
  4. That sucks

The output is:

This is a line
That sucks
That sucks
That sucks
This is a line

My Code:

# Variable for text file
text_database = './text_database.txt'

# Elif instruction for random lines from file
elif command == '/random':
    with open (text_database) as f:
        lines = f.readlines()
        print(random.choise(lines))

What I tried:

elif command == '/random':
    lines_list = []
    with open (text_database) as f:
        lines = f.readlines()
        random_tmp = random.choice(lines)
        lines_list.append(random_tmp)
        if random_tmp not in lines_list:
            print(random_tmp)

It don't work and I need help. Thank you guys.




Aucun commentaire:

Enregistrer un commentaire