Pregunta

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
¿Fue útil?

Solución

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)

Otros consejos

Have you looked at distutils.dir_util.copy_tree()? The update parameter is defaulted to 0 but it seems like you'd want 1, which would only copy if files don't exist at the destination or are older. I don't see any requirement in your question that copy_tree() won't cover.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top