How to copy file without overwriting destination file using Python shutil
Purpose
In this post, I will demonstrate how to copy files using Python’s shutil
module, and how to copy files without overwriting the destination file.
The Environment
- Python 3
- Shutil
The code
How to copy a file?
This is a demo that shows how to copy a file from src
to dest
:
Test the copy function
Suppose our working directory structure is as follows:
Now we want to copy logo.png
to the images
directory and name it logo_bak.png
. We can do this as follows:
After running the above command, we get this directory structure:
How to copy without overwriting
The code:
Test the copy again
Our directory structure is:
Then we execute the following command in the working directory:
It works!
About the shutil
Shutil module in Python provides many high-level operations on files and collections of files. This module helps in automating the process of copying and removal of files and directories. The shutil.copy()
method in Python is used to copy the content of the source file to the destination file or directory.
Shutil is the abbreviation of shell utility, which implements advanced functions such as file copying, moving, compression, and decompression in Python. It is a Python system module and does not require additional installation.
The commonly used functions in shutil
are listed below:
shutil.copyfile(src, dst)
: Copy from sourcesrc
todst
. If the destination file already exists, it will be overwritten.shutil.move(src, dst)
: Move a file or rename it.shutil.copymode(src, dst)
: Copy file permissions, but not the file content.shutil.copystat(src, dst)
: Copy file permissions, last access time, and last modification time.shutil.copy(src, dst)
: Copy a file to a file or a directory.shutil.copy2(src, dst)
: Similar toshutil.copy()
, but also copies the last access time and modification time.shutil.copytree(olddir, newdir, True/False)
: Copy a directory tree. If the third parameter isTrue
, symbolic links are preserved.shutil.rmtree(src)
: Recursively delete a directory and all its contents.
Summary
In this post, we demonstrated how to use the shutil
module in Python to copy files from one location to another. We also showed how to avoid overwriting the destination file during the copy operation. The shutil
module is a powerful tool for file operations in Python, and it simplifies tasks like copying, moving, and deleting files and directories.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!