You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it with os for more control over paths.
Below are the most common methods:
Method 1: Using shutil.copy()
Copy a file to another location preserving the content but not metadata
python
import shutilshutil.copy(“source.txt”, “destination.txt”)
Use when you just need a quick copy and don’t care about original file metadata.
Method 2: Using shutil.copy2() for Metadata
Like copy(), but preserve file metadata (timestamps, permissions etc.)
python
import shutilshutil.copy2(“source.txt”, “destination.txt”)
For backups or when file metadata matters.
Also Read: Python Developer Hourly Rate
Method 3: Copy File to Directory
Copy a file into a directory by providing the destination folder path
python
import shutilshutil.copy(“source.txt”, “/path/to/folder/”)
Python will put the copied file in the target folder with the original filename.
Method 4: Use os with shutil for Dynamic Paths
Useful when building paths programmatically before copying
python
import osimport shutil
src = “source.txt”
dst = os.path.join(“backup”, src)
shutil.copy2(src, dst)
Combines dynamic path handling with safe file copy.
Also Read:
Tip
- Always check if the destination path exists before copying to avoid overwriting.
- For directories use shutil.copytree() to copy entire folders.
- pathlib can also be used with Path.write_text() or Path.write_bytes() for custom logic.