How to copy file without overwriting destination file using python shutils?
1. Purpose
In this post, I will demonstrate how to copy file using python shutils
, and will also show you how to copy without overwriting the destination file
.
2. The Environment
- Python 3
- Shutils
3. The code
3.1 How to copy file?
This is the demo that shows how to copy file from src to dest:
3.2 Test the copy function
Suppose our working directory structure as follows:
Now I want to copy logo.png
to images
directory, and name it logo_bak.png
, I do this job as follows:
After run the above command, I get this directory structure:
3.3 How to copy without overwritten
The code:
3.4 Test the copy again
Our directory is :
Then I execute the below command in the working directory:
It works!
4. About the shutil
Shutil module in Python provides many functions of high-level operations on files and collections of files. … This module helps in automating process of copying and removal of files and directories. shutil. copy() method in Python is used to copy the content of source file to 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 source src to dst. Of course, the premise is that the target address has writable permissions. The exception information thrown is IOException. If the current dst already exists, it will be overwrittenshutil.move(src, dst)
move file or renameshutil.copymode(src, dst)
just copy its permissions and other things will not be copiedshutil.copystat(src, dst)
copy permission, last access time, last modification timeshutil.copy(src, dst)
copy a file to a file or a directoryshutil.copy2(src, dst)
is copied on the basis of copy and the last access time and modification time of the file are also copied, similar to cp -pshutil.copy2(src, dst)
If the file systems in the two locations are the same, it is equivalent to a rename operation, just rename; if it is not in the same file system, it is a move operationshutil.copytree(olddir, newdir, True/Flase)
copies olddir to newdir. If the third parameter is True, the symbolic link under the folder will be kept when copying the directory. If the third parameter is False, it will Generate a physical copy in the copied directory to replace the symbolic linkshutil.rmtree(src)
recursively delete a directory and all contents in the directory
5. Summary
In this post, I demonstrated how to use shutil
in python to copy files from here to there. And I also demonstrated how to avoid overwriting the dest file when copying. Thanks for your reading. Regards.