Created
November 13, 2018 05:58
-
-
Save NanoDano/32bb3ba25b2bd5cdf192542660ac4de0 to your computer and use it in GitHub Desktop.
Python 3 recursively copy one directory to another that may already exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# copy_recursive.py | |
import os | |
import shutil | |
import sys | |
from pathlib import Path | |
def copy_recursive(source_base_path, target_base_path): | |
""" | |
Copy a directory tree from one location to another. This differs from shutil.copytree() that it does not | |
require the target destination to not exist. This will copy the contents of one directory in to another | |
existing directory without complaining. | |
It will create directories if needed, but notify they already existed. | |
If will overwrite files if they exist, but notify that they already existed. | |
:param source_base_path: Directory | |
:param target_base_path: | |
:return: None | |
""" | |
if not Path(source_base_path).is_dir() or not Path(target_base_path).is_dir(): | |
raise Exception("Source and destination directory and not both directories.\nSource: %s\nTarget: %s" % ( | |
source_base_path, target_base_path)) | |
for item in os.listdir(source_base_path): | |
# Directory | |
if os.path.isdir(os.path.join(source_base_path, item)): | |
# Create destination directory if needed | |
new_target_dir = os.path.join(target_base_path, item) | |
try: | |
os.mkdir(new_target_dir) | |
except OSError: | |
sys.stderr.write("WARNING: Directory already exists:\t%s\n" % new_target_dir) | |
# Recurse | |
new_source_dir = os.path.join(source_base_path, item) | |
copy_recursive(new_source_dir, new_target_dir) | |
# File | |
else: | |
# Copy file over | |
source_name = os.path.join(source_base_path, item) | |
target_name = os.path.join(target_base_path, item) | |
if Path(target_name).is_file(): | |
sys.stderr.write("WARNING: Overwriting existing file:\t%s\n" % target_name) | |
shutil.copy(source_name, target_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment