Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

randomly choose 100 documents under a directory

There are about 2000 documents under the directory. I want to randomly select some documents and copy them to a new directory automatically.

Some relevant information about generating one document name under a certain directory.

like image 337
juju Avatar asked Jul 07 '12 03:07

juju


People also ask

How do I select random files in a folder?

Right-click the folder in the left-hand pane — not the right — and click the new “Select Random” option. RandomSelectionTool then selects something from the contents of that folder — either a file, or a folder — and the right-hand pane should be updated to display it.

How do you select random images in python?

Example to show a random picture from a folder in Python: First, you select the path of the folder where the picture is present like->c\\user\\folder. By using the listdir() method store all the images present in the folder. By using random. choice() method to select a image and os.


2 Answers

Try:

import shutil, random, os
dirpath = 'your/read/location'
destDirectory = 'your/destination'

filenames = random.sample(os.listdir(dirpath), 100)
for fname in filenames:
    srcpath = os.path.join(dirpath, fname)
    shutil.copyfile(srcpath, destDirectory)
like image 107
inspectorG4dget Avatar answered Oct 17 '22 17:10

inspectorG4dget


import shutil, random, os
dirpath = 'your/read/location'
destDirectory = 'your/destination'

filenames = random.sample(os.listdir(dirpath), 100)
for fname in filenames:
    srcpath = os.path.join(dirpath, fname)
    destPath = os.path.join(destDirectory, fname)
    shutil.copyfile(srcpath, destPath)

Based off the answer by @inspectorG4dget (and edited by @olinox14), I found this minor adjustment worked best for my situation. I kept getting a 'IsDirectoryError' from shutil.copyfile() so I checked out the docs and realized the function copies to files (not directories). This adjustment preserves the filename in a new directory.

like image 2
zoot-io Avatar answered Oct 17 '22 18:10

zoot-io