Skip to content
Advertisement

Get ‘n’ Unique random lines from a text file using python

I have a text file with ~1000 lines, and i wanted to take unique (not repeating) random 15 lines from the text file.

I tried this.

from random import choice
lines = [a.strip() for a in open("FailsCollection.txt").readlines()]
result = [choice(lines) for a in range(15)]

but this was not selecting unique lines, sometimes the same line was repeating in the 15 lines output.

from the answer here I tried this also

import random
from random import choice
lines = [a.strip() for a in open("FailsCollection.txt").readlines()]
result = [choice(lines) for a in random.sample(range(1, 1000), 15)]

But again the lines were not unique.

Can anyone please advice. Thanks in advance.

Advertisement

Answer

Simple one:

import random

with open("FailsCollection.txt") as f:
    result = random.sample(list(f), 15)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement