Last active
May 23, 2016 12:32
-
-
Save bharadwaj-raju/967e9127533679f36c34a2647b0dfbcc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Script to copy n random folders to a location | |
# Usage: RandomCopier.py [source folder] [destination folder] [number to copy] | |
import os | |
import sys | |
import shutil | |
import random | |
try: | |
src_dir = os.path.abspath(sys.argv[1]) | |
dest_dir = os.path.abspath(sys.argv[2]) | |
number_to_copy = int(sys.argv[3]) | |
except: | |
print('Usage: %s [source folder] [destination folder] [number to copy]' % sys.argv[0]) | |
sys.exit(1) | |
print('Copying %d folders from %s to %s.' % (number_to_copy, src_dir, dest_dir)) | |
src_dir_list = [d for d in os.listdir(src_dir) if os.path.isdir(os.path.join(src_dir, d))] | |
print('Clearing destination directory.') | |
# Clear destination | |
for file in os.listdir(dest_dir): | |
file_path = os.path.join(dest_dir, file) | |
if os.path.isfile(file_path): | |
os.unlink(file_path) | |
elif os.path.isdir(file_path): | |
shutil.rmtree(file_path) | |
# Custom directory copier, re-implements shutil.copytree | |
# such that it copies sub-folders into destination | |
def dir_copy(src, dest, ignore=None): | |
if os.path.isdir(src): | |
if not os.path.isdir(dest): | |
os.makedirs(dest) | |
files = os.listdir(src) | |
if ignore is not None: | |
ignored = ignore(src, files) | |
else: | |
ignored = set() | |
for f in files: | |
if f not in ignored: | |
dir_copy(os.path.join(src, f), | |
os.path.join(dest, f), | |
ignore) | |
else: | |
shutil.copyfile(src, dest) | |
random.shuffle(src_dir_list) | |
for i in range(number_to_copy): | |
# Since the list is randomized, we choose first i from list | |
print('Copying %s.' % src_dir_list[i]) | |
rand_dir_path = os.path.join(src_dir, src_dir_list[i]) | |
dir_copy(rand_dir_path, os.path.join(dest_dir, src_dir_list[i])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment