Created
May 23, 2016 11:54
-
-
Save bharadwaj-raju/15e4b1b77094a1324d732c7ef970fcb7 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 | |
import distutils | |
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 the_file in os.listdir(dest_dir): | |
file_path = os.path.join(dest_dir, the_file) | |
if os.path.isfile(file_path): | |
os.unlink(file_path) | |
#elif os.path.isdir(file_path): shutil.rmtree(file_path) | |
# Custom directory copier, interface to shutil.copytree | |
def copytree(src, dst, symlinks=False, ignore=None): | |
for item in os.listdir(src): | |
s = os.path.join(src, item) | |
d = os.path.join(dst, item) | |
if os.path.isdir(s): | |
shutil.copytree(s, d, symlinks, ignore) | |
else: | |
shutil.copy2(s, d) | |
def recursive_overwrite(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: | |
recursive_overwrite(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]) | |
recursive_overwrite(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