I am interested in copying random files from a Directory Tree. I tried example below and it works terrific for 1 directory of files, however I want it to search through multiple sub-directories and do the same thing.
Example: Selecting and Copying a Random File Several Times
I was trying to work out how to use either os.walk or shutil.copytree but not sure what to do. Thanks in advance!
import os
import shutil
import random
import os.path
src_dir = 'C:\\'
target_dir = 'C:\\TEST'
src_files = (os.listdir(src_dir))
def valid_path(dir_path, filename):
full_path = os.path.join(dir_path, filename)
return os.path.isfile(full_path)
files = [os.path.join(src_dir, f) for f in src_files if valid_path(src_dir, f)]
choices = random.sample(files, 5)
for files in choices:
shutil.copy(files, target_dir)
print ('Finished!')
I have updated this however I notice that os.walk is only giving me the last directory in the tree which has 5 files instead of 15 total from the root directory. Not sure where I am going wrong here:
import os
import shutil
import random
source_dir = "C:\\test\\from"
target_dir = "C:\\test\\to"
for path, dirs, filenames in os.walk(source_dir):
source_files = filenames
print(source_files) # this gives me 15 files whih is correct
print(source_files) # this gives me only 5 files which is only the last directory
choices = random.sample(source_files, 5)
print(choices)
for files in choices:
shutil.copy(files, target_dir)