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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With