To copy a file in Python for a source location to a destination, you can use the shutil module.
Example (macOS/Linux):
import shutil
source_path = "/user/c2c/files/myfile.txt"
destination_path = "/user/c2c/archives/myfile.txt"
# copy files from source to destination using shutil.copy
shutil.copy(source_path, destination_path)
Example (Windows):
import shutil
source_path = "D:/c2c/files/myfile.txt"
destination_path = "D:/c2c/archives/myfile.txt"
shutil.copy(source_path, destination_path)
Note: the file to be copied to the destination path already exists, shutil.copy will overwrite it.
Note: If the source or destination file does not exists, you will get FileNotFoundError.
Traceback (most recent call last):
File "/Users/c2ctech/Desktop/example.py", line 7, in <module>
shutil.copy(source_path, destination_path)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/shutil.py", line 418, in copy
..
..
FileNotFoundError: [Errno 2] No such file or directory: '/user/c2c/files/myfile.txt'
Traceback (most recent call last):
File "/Users/c2ctech/Desktop/example.py", line 7, in <module>
shutil.copy(source_path, destination_path)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/shutil.py", line 418, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/shutil.py", line 264, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/archives/myfile.txt'
In order to copy the file with a new name, you can specify the new file name in the destination path. For example, if you want to copy myfile.txt to the destination directory with a new name archived_myfile.txt, follow the below code.
import os
import shutil
source_path = "D:/c2c/files/myfile.txt"
destination_path = "D:/c2c/archives/archive_myfile.txt"
# Create the destination directory if it does not exist
os.makedirs(os.path.dirname(destination_path), exist_ok=True)
# Copy the file to destination
copied_path = shutil.copy(source_path, destination_path)
print(f"file copied to: {copied_path}")
Output:
file copied to: D:/c2c/archives/archive_myfile.txt
The method returns the path to the newly created file.
copy() copies the file data and the file’s permission mode, metadata, such as the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.
copied_path = shutil.copy2(source_path, destination_path)
Reference
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
- Android: Maps and Places using Maps SDK - Android
- How to add or remove bookmark on a line in Notepad++ - NotepadPlusPlus
- Okta Hacked - Source Code Stolen from GitHub Repo - News
- Generate Project Dependency tree using Gradle Command - Gradle
- Get MD5 Hash as Checksum of a String in Python - Python
- How to Show Path of Files or App in Mac Spotlight Search - MacOS
- How to insert image into Google Sheets cell - Google
- How to exit from nano command - Linux