Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: copy folder content recursively

I want to copy the content of a folder recursively without copying files that already exist. Also, the destination Folder already exists and contains files. I tried to use shutils.copytree(source_folder, destination_folder), but it does not do what I want.

I want it to work like this:

Before:

  • source_folder
    • sub_folder_1
      • foo
      • bar
    • sub_folder_2

  • destination_folder
    • folder_that_was_already_there
      • file2.jpeg
    • some_file.txt
    • sub_folder_1
      • foo

After:

  • destination_folder
    • folder_that_was_already_there
      • file2.jpeg
    • some_file.txt
    • sub_folder_1
      • foo
      • bar
    • sub_folder_2
like image 929
malt3 Avatar asked May 17 '26 14:05

malt3


1 Answers

I found the answer with the help of tdelaney:
source_folder is the path to the source and destination_folder the path to the destination.

import os
import shutil

def copyrecursively(source_folder, destination_folder):
for root, dirs, files in os.walk(source_folder):
    for item in files:
        src_path = os.path.join(root, item)
        dst_path = os.path.join(destination_folder, src_path.replace(source_folder, ""))
        if os.path.exists(dst_path):
            if os.stat(src_path).st_mtime > os.stat(dst_path).st_mtime:
                shutil.copy2(src_path, dst_path)
        else:
            shutil.copy2(src_path, dst_path)
    for item in dirs:
        src_path = os.path.join(root, item)
        dst_path = os.path.join(destination_folder, src_path.replace(source_folder, ""))
        if not os.path.exists(dst_path):
            os.mkdir(dst_path)
like image 113
malt3 Avatar answered May 20 '26 03:05

malt3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!