While the above methods work, you might encounter scenarios where you want greater control, such as handling symlinks or copying selective content. In such cases, you can create a custom recursive function using os.walk() to replicate the functionality of Unix cp -r:
import shutil
import os
def copy_recursive(src, dst):
if os.path.isfile(src):
shutil.copy(src, dst)
elif os.path.isdir(src):
os.makedirs(dst, exist_ok=True)
for root, dirs, files in os.walk(src):
dst_dir = os.path.join(dst, os.path.relpath(root, src))
os.makedirs(dst_dir, exist_ok=True)
for file in files:
shutil.copy(os.path.join(root, file), os.path.join(dst_dir, file))
# Example usage:
copy_recursive('source_folder', 'destination_folder')
copy_recursive('file.txt', 'destination_file.txt')
This approach mimics the recursive nature of Unix cp -r, providing flexibility to handle special cases like nested directories or permissions. It’s the most customizable solution for those needing granular control in their Python copy directory operations.