How to Copy a File in Python with Shutil

Copy a File with shutil.copy()

Use shutil.copy(src, dest) to copy a file to a destination while preserving the content but not metadata like permissions.

Copy a shutilFile with Metadata Using .copy2()

shutil.copy2(src, dest) copies the file and its metadata, including timestamps and permissions, for more precise duplication.

Copy Only File Permissions with shutil.copymode()

To copy just the permissions, use shutil.copymode(src, dest) without altering content or other metadata.

Copy File Content Only with shutil.copyfile()

Use shutil.copyfile(src, dest) for copying only file data without metadata or permissions, ideal for creating fresh copies.

Recursive Copy with shutil.copytree()

For copying entire directories, use shutil.copytree(src, dest) to duplicate a directory and all its subdirectories.

Handle Errors with try-except

Wrap shutil operations in a try-except block to handle errors, such as missing files or permission issues, gracefully.