Python | shutil.copy() method
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil# Source pathsource = "/home/User/Documents/file.txt"# Destination pathdestination = "/home/User/Documents/file.txt"# Copy the content of# source to destinationtry: shutil.copy(source, destination) print("File copied successfully.")# If source and destination are sameexcept shutil.SameFileError: print("Source and destination represents the same file.")# If there is any permission issueexcept PermissionError: print("Permission denied.")# For other errorsexcept: print("Error occurred while copying file.") |
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. 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. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved.
Source must represent a file but destination can be a file or a directory. If the destination is a directory then the file will be copied into destination using the base filename from source. Also, destination must be writable. If destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created.
Syntax: shutil.copy(source, destination, *, follow_symlinks = True)
Parameter:
source: A string representing the path of the source file.
destination: A string representing the path of the destination file or directory.
follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘follow_symlinks’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method returns a string which represents the path of newly created file.
Code #1: Use of shutil.copy() method to copy file from source to destination
Python3
# Python program to explain shutil.copy() method # importing os moduleimport os# importing shutil moduleimport shutil# pathpath = '/home/User/Documents'# List files and directories# in '/home/User/Documents'print("Before copying file:")print(os.listdir(path))# Source pathsource = "/home/User/Documents/file.txt"# Print file permission# of the sourceperm = os.stat(source).st_modeprint("File Permission mode:", perm, "\n")# Destination pathdestination = "/home/User/Documents/file(copy).txt"# Copy the content of# source to destinationdest = shutil.copy(source, destination)# List files and directories# in "/home / User / Documents"print("After copying file:")print(os.listdir(path))# Print file permission# of the destinationperm = os.stat(destination).st_modeprint("File Permission mode:", perm)# Print path of newly# created fileprint("Destination path:", dest) |
Before copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp'] File permission mode: 33188 After copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp'] File permission mode: 33188 Destination path: /home/User/Documents/file(copy).txt
Code #2: If destination is a directory
Python3
# Python program to explain shutil.copy() method # importing os moduleimport os# importing shutil moduleimport shutil# Source pathsource = "/home/User/Documents/file.txt"# Destination pathdestination = "/home/User/Desktop/"# Copy the content of# source to destinationdest = shutil.copy(source, destination)# List files and directories# in "/home / User / Desktop"print("After copying file:")print(os.listdir(destination))# Print path of newly# created fileprint("Destination path:", dest) |
After copying file: ['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp'] Destination path: /home/User/Desktop/file.txt
Code #3: Possible errors while using shutil.copy() method
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil# If the source and destination# represents the same file# 'SameFileError' exception# will be raised# If the destination is# not writable# 'PermissionError' exception# will be raised# Source pathsource = "/home/User/Documents/file.txt"# Destination pathdestination = "/home/User/Documents/file.txt"# Copy the content of# source to destinationshutil.copy(source, destination) |
Traceback (most recent call last):
File "try.py", line 26, in
dest = shutil.copy(source, destination)
File "/usr/lib/python3.6/shutil.py", line 241, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.6/shutil.py", line 104, in copyfile
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: '/home/User/Desktop/file.txt' and '/home/User/Desktop/file.txt'
are the same file
Code #4: Handling errors while using shutil.copy() method
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil# Source pathsource = "/home/User/Documents/file.txt"# Destination pathdestination = "/home/User/Documents/file.txt"# Copy the content of# source to destinationtry: shutil.copy(source, destination) print("File copied successfully.")# If source and destination are sameexcept shutil.SameFileError: print("Source and destination represents the same file.")# If there is any permission issueexcept PermissionError: print("Permission denied.")# For other errorsexcept: print("Error occurred while copying file.") |
Source and destination represents the same file.
Reference: https://docs.python.org/3/library/shutil.html



