import argparse from os import listdir, makedirs from os.path import isfile, join, splitext, dirname, realpath from shutil import move as shmove def get_all_file_names(dir_name, extension): """Retrieve the list of all file names in a directory matching an ext.""" only_files = [f for f in listdir(dir_name) if isfile(join(dir_name, f))] only_names = [splitext(f)[0] for f in only_files if splitext(f)[1] == '.'+extension] return only_names def make_dirs(root_dir_name, dir_list): """Make folders based on file names.""" for dir_name in dir_list: d = join(root_dir_name, dir_name) makedirs(d, exist_ok=True) def move_files(root_dir_name, dir_list, extension): """Move files from the root folder to a folder based on the file name.""" for name in dir_list: source = join(root_dir_name, name+'.'+extension) target = join(root_dir_name, name) shmove(source, target) def current_dir(): """Return the directory of the current file.""" return dirname(realpath(__file__)) # Begin main control if __name__ == '__main__': # Setup commandline args parser = argparse.ArgumentParser( description='Copy files from root folder to subfolders', add_help=False) parser.add_argument( '-?', '--help', action='help', help='Show this help message and exit') parser.add_argument( '-d', '--directory', default=current_dir(), type=str, help='Specify directory to perform operation. Defaults to current dir.' ) parser.add_argument( '-x', '--extension', default='tif', type=str, help='The type of file to move.' ) # get args args = parser.parse_args() upc_list = get_all_file_names(args.directory, args.extension) print(upc_list) make_dirs(args.directory, upc_list) move_files(args.directory, upc_list, args.extension)