Reputation: 91
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:
After:
Upvotes: 3
Views: 7424
Reputation: 444
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.
Upvotes: 0
Reputation: 91
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)
Upvotes: 3