Home > Software design >  Is there a command to select a file randomly but only once?
Is there a command to select a file randomly but only once?

Time:08-29

I want my program to select 150 files and zip these files, but it should not select duplicate files. In fact, I want a file to be selected only once!

CodePudding user response:

You could use random.sample and zipfile:

import pathlib
import random
import zipfile
DIR = pathlib.Path("your/dir") # The dir with the files to select from
files = random.sample([file for file in DIR.listdir() if file.is_file()], 150)
with zipfile.ZipFile("output.zip", "w") as zip:
    for file in files:
        zip.write(file)

CodePudding user response:

Generate a random number in range 1 to length of your file list, and use this number to index a file in your list. Pop the file from your list and perform this procedure again.

  • Related