0

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.

srk_cb
  • 247
  • 2
  • 7
  • 1
    Does this answer your question? [Python random N lines from large file (no duplicate lines)](https://stackoverflow.com/questions/12279017/python-random-n-lines-from-large-file-no-duplicate-lines) – J. M. Arnold Feb 08 '21 at 11:41
  • You know `sample`, so use it on the lines? – Kelly Bundy Feb 08 '21 at 11:42
  • @J.M.Arnold That one seems much harder, though, and the answers there more complicated than necessary here (as they're trying to be efficient). – Kelly Bundy Feb 08 '21 at 11:44
  • 2
    *"sometimes the same line was repeating in the 15 lines output"* - That's rather impossible to believe. Randomly picking the same line out of 1000 lines 15 times in a row is extremely unlikely. – Kelly Bundy Feb 08 '21 at 11:54

2 Answers2

2

Simple one:

import random

with open("FailsCollection.txt") as f:
    result = random.sample(list(f), 15)
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • yes this worked.. Great, thanks alot. and also thanks for the comments on the other question moderator pointed to. that question was not helping me . – srk_cb Feb 08 '21 at 12:02
1

Use random.sample

Try this code:

from random import sample
n=15
indexes = random.sample(range(0,1000),n)
file = open("FailsCollection.txt").readlines()
lines = []
for i in indexes:
   lines.append(file[i].strip())
print(lines)
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26