Merge 2 directories and overwrite files with same name

41 Views Asked by At

I'm trying to find a way to merge one directory into another one, and if a file has the same name then just overwrite it.

So far the best that I could come up with is this:

def merge(folder1: str, folder2: str):
    for filename in os.listdir(folder1):
        file_path = os.path.join(folder1, filename)
        new_file_path = os.path.join(folder2, filename)
        if os.path.exists(new_file_path):
            if os.path.isdir(new_file_path):
                shutil.rmtree(new_file_path)
            else:
                os.remove(new_file_path)
        try:
            if os.path.isfile(file_path):
                shutil.copy2(file_path, new_file_path)
            elif os.path.isdir(file_path):
                shutil.copytree(file_path, new_file_path)
        except Exception as e:
            print('Failed to copy %s. Reason: %s' % (file_path, e))

The issue with this is that it's not recursive and will just replace an entire directory if there is one with the same name instead of looking into the directory.

(Sorry but I couldn't find a better way to explain it)

0

There are 0 best solutions below