Skip to content

Instantly share code, notes, and snippets.

@bykof
Last active April 21, 2016 09:13
Show Gist options
  • Save bykof/f2527d965bb1d148c6b84321007c7d70 to your computer and use it in GitHub Desktop.
Save bykof/f2527d965bb1d148c6b84321007c7d70 to your computer and use it in GitHub Desktop.
Copy or move all files from a folder and subfolders to one source folder and don't overwrite duplicate files
import os
import shutil
import click
def copy_or_move_files_from_folder_to_folder(from_folder, to_folder, task='copy', recursive=True):
for current_file in os.listdir(from_folder):
path_to_source = os.path.join(from_folder, current_file)
path_to_destination = os.path.join(to_folder, current_file)
if os.path.isfile(path_to_source):
if os.path.exists(path_to_destination):
splitted_dest = path_to_destination.split('.')
try:
last_number = int(splitted_dest[-2][-1])
if last_number < 9:
splitted_dest[-2] = splitted_dest[-2][:-1] + str(last_number + 1)
else:
splitted_dest[-2] += str(0)
except ValueError:
splitted_dest[-2] += str(0)
path_to_destination = '.'.join(splitted_dest)
if task == 'copy':
shutil.copyfile(path_to_source, path_to_destination)
if task == 'move':
shutil.move(path_to_source, path_to_destination)
else:
if recursive:
copy_or_move_files_from_folder_to_folder(path_to_source, to_folder)
@click.command()
@click.option('--src', help='The source directory. (absolute path)')
@click.option('--dest', help='The destination directory. (absolute path)')
@click.option('--task', help='Move your files or copy? (move, copy)')
@click.option('--recursive', help='Move or copy recursive? (True, False) [standard: True]', )
def copy_or_move_files_to_one_dir(src, dest, task, recursive):
"""A programm that copies recursively files from folders and subfolders to one folder"""
if not os.path.exists(src):
click.echo('The given source path doesn\'t exist!', err=True)
if not os.path.exists(dest):
click.echo('The given destination path doesn\'t exist!', err=True)
if not recursive:
recursive = True
if not task or task not in ['move', 'copy']:
task = 'copy'
copy_or_move_files_from_folder_to_folder(src, dest, task, recursive)
if __name__ == '__main__':
copy_or_move_files_to_one_dir()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment