Skip to content

Instantly share code, notes, and snippets.

@megalucio
Last active February 11, 2021 14:49
Show Gist options
  • Save megalucio/618bd09ba3b4bae2d534881d9336c441 to your computer and use it in GitHub Desktop.
Save megalucio/618bd09ba3b4bae2d534881d9336c441 to your computer and use it in GitHub Desktop.
Copies files from one folder(new_folder) to another(main_folder) making sure that if there is a duplicate it doesn't get overwritten but instead copied with a different name.
#!/usr/bin/env python
# Copies files from one folder(new_folder) to another(main_folder) making sure that
# if there is a duplicate it doesn't get overwritten but instead copied with a different name.
import os
import filecmp
import shutil
import glob
import sys
# Looks for a file in a path
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
# Gets a list of files in a folder excluding hidden ones
def listdir_nohidden(path):
return glob.glob(os.path.join(path, '*'))
# Check/process arguments
if len(sys.argv) != 3:
print('Usage: python ' + sys.argv[0] + ' main_folder destination_folder')
sys.exit()
main_folder = os.path.sys.argv[1]
new_folder = sys.argv[2]
# Copies each file in the new_folder into main_folder accordingly
new_files = listdir_nohidden(new_folder)
for new_file in new_files:
existing_file = find(os.path.basename(new_file), main_folder)
# if file does not exist copy to destination folder
if(existing_file is None):
shutil.copy(new_file,main_folder)
# if exists and it is differetn, rename it to destination folder
elif(not filecmp.cmp(new_file, existing_file)):
shutil.copy(new_file, os.path.join(main_folder, 'renamed.' + os.path.basename(new_file)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment