Python | shutil.copyfile() method - GeeksforGeeks

20 Jun, 2021
Python3
# Python program to explain shutil.copyfile() method   # importing shutil moduleimport shutil # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Documents" # Copy the content of# source to destination try:    shutil.copyfile(source, destination)    print("File copied successfully.") # If source and destination are sameexcept shutil.SameFileError:    print("Source and destination represents the same file.") # If destination is a directory.except IsADirectoryError:    print("Destination is a directory.") # 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.copyfile() method in Python is used to copy the content of source file to destination file. Metadata of the file is not copied. Source and destination must represent a file and destination must be writable. If destination already exists then it will be replaced with the source file otherwise a new file will be created. If source and destination represents the same file then SameFileError exception will be raised.  
Syntax: shutil.copyfile(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. follow_symlinks (optional) : The default value of this parameter is True. If False and source represents a symbolic link then a new symbolic link will be created instead of copying the file.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.copyfile() method to copy file from source to destination  
Python3
# Python program to explain shutil.copyfile() 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" # Destination pathdestination = "/home/User/Documents/file(copy).txt" # Copy the content of# source to destinationdest = shutil.copyfile(source, destination) # List files and directories# in "/home / User / Documents"print("After copying file:")print(os.listdir(path)) # Print path of newly# created fileprint("Destination path:", dest)
Before copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp']
After copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
Destination path: /home/User/Documents/file(copy).txt
 
Code #2: Possible errors while using shutil.copyfile() method  
Python3
# Python program to explain shutil.copyfile() method   # importing shutil moduleimport shutil  # If the source and destination# represents the same file# 'SameFileError' exception# will be raised # If the destination is# is directory then# 'IsADirectoryError' 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.copyfile(source, destination)
Traceback (most recent call last):
  File "copy.py", line 31, in 
    shutil.copyfile(source, destination)
  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/Documents/file.txt' and '/home/User/Documents/file.txt'
are the same file
 
Code #3: Handling errors while using shutil.copyfile() method  
Python3
# Python program to explain shutil.copyfile() method   # importing shutil moduleimport shutil # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Documents" # Copy the content of# source to destination try:    shutil.copyfile(source, destination)    print("File copied successfully.") # If source and destination are sameexcept shutil.SameFileError:    print("Source and destination represents the same file.") # If destination is a directory.except IsADirectoryError:    print("Destination is a directory.") # If there is any permission issueexcept PermissionError:    print("Permission denied.") # For other errorsexcept:    print("Error occurred while copying file.")
Destination is a directory.
 
Reference: https://docs.python.org/3/library/shutil.html 
surindertarika1234
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications