Created
September 19, 2025 18:54
-
-
Save gekkedev/d4d6ff488e131491b254bf381e06c986 to your computer and use it in GitHub Desktop.
Copy files from Folder A to C if not present in B (Python >=3.2)
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
| import os | |
| import shutil | |
| import argparse | |
| def copy_unique_files(folder_a: str, folder_b: str, folder_c: str, recursive: bool = False) -> None: | |
| """Copy files from folder_a to folder_c if they do not exist in folder_b.""" | |
| os.makedirs(folder_c, exist_ok=True) | |
| if recursive: | |
| files_in_b = { | |
| os.path.relpath(os.path.join(root, f), folder_b) | |
| for root, _, files in os.walk(folder_b) | |
| for f in files | |
| } | |
| for root, _, files in os.walk(folder_a): | |
| rel_dir = os.path.relpath(root, folder_a) | |
| dest_dir = os.path.join(folder_c, rel_dir) | |
| os.makedirs(dest_dir, exist_ok=True) | |
| for f in files: | |
| rel_path = os.path.join(rel_dir, f) | |
| src_path = os.path.join(root, f) | |
| dest_path = os.path.join(dest_dir, f) | |
| if rel_path not in files_in_b: | |
| shutil.copy2(src_path, dest_path) | |
| print(f"Copied: {rel_path}") | |
| else: | |
| print(f"Skipped: {rel_path}") | |
| else: | |
| files_in_b = set(os.listdir(folder_b)) | |
| for f in os.listdir(folder_a): | |
| src_path = os.path.join(folder_a, f) | |
| dest_path = os.path.join(folder_c, f) | |
| if os.path.isfile(src_path) and f not in files_in_b: | |
| shutil.copy2(src_path, dest_path) | |
| print(f"Copied: {f}") | |
| else: | |
| print(f"Skipped: {f}") | |
| print("\n✅ Copy operation complete.") | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Copy files from folder A to folder C if they don't exist in folder B." | |
| ) | |
| parser.add_argument("folder_a", help="Source folder (A)") | |
| parser.add_argument("folder_b", help="Comparison folder (B)") | |
| parser.add_argument("folder_c", help="Destination folder (C)") | |
| parser.add_argument( | |
| "-r", "--recursive", action="store_true", help="Enable recursive mode (include subfolders)" | |
| ) | |
| args = parser.parse_args() | |
| copy_unique_files(args.folder_a, args.folder_b, args.folder_c, args.recursive) | |
| # importable pattern | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment