Python | shutil.copy2() method
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.copy2() method in Python is used to copy the content of source file to destination file or directory. This method is identical to shutil.copy() method but it also try to preserves the file’s metadata.
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.copy2(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 it attempts to copy all metadata from the source symbolic link to the newly-created destination symbolic link. This functionality is platform dependent.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.
# Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # path path = '/home/User/Documents' # List files and directories # in '/home/User/Documents' print("Before copying file:") print(os.listdir(path)) # Source path source = "/home/User/Documents/file.txt" # Print the metadeta # of source file metadata = os.stat(source) print("Metadata:", metadata, "\n") # Destination path destination = "/home/User/Documents/file(copy).txt" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in "/home / User / Documents" print("After copying file:") print(os.listdir(path)) # Print the metadata # of the destination file matadata = os.stat(destination) print("Metadata:", metadata) # Print path of newly # created file print("Destination path:", dest) |
Before copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp'] Metadata: os.stat_result(st_mode=33188, st_ino=801113, st_dev=2056, st_nlink=1, st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156, st_ctime=1558866156) After copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp'] Metadata: os.stat_result(st_mode=33188, st_ino=801111, st_dev=2056, st_nlink=1, st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156, st_ctime=1558933947) Destination path: /home/User/Documents/file(copy).txt
# Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Desktop/" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in "/home / User / Desktop" print("After copying file:") print(os.listdir(destination)) # Print path of newly # created file print("Destination path:", dest) |
After copying file: ['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp'] Destination path: /home/User/Desktop/file.txt
# Python program to explain shutil.copy2() method # importing shutil module import 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 path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination shutil.copy2(source, destintion) |
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 copy2
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
# Python program to explain shutil.copy2() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy2(source, destination) print("File copied successfully.") # If source and destination are same except shutil.SameFileError: print("Source and destination represents the same file.") # If there is any permission issue except PermissionError: print("Permission denied.") # For other errors except: print("Error occurred while copying file.") |
Source and destination represents the same file.
Reference: https://docs.python.org/3/library/shutil.html
Recommended Posts:
- class method vs static method in Python
- Python | os.dup() method
- Python | set() method
- Python | next() method
- Python PIL | ImageOps.fit() method
- Python | os.major() method
- Python | os.minor() method
- Python | cmath.exp() method
- Python | cmath.log() method
- Python Dictionary | pop() method
- Python | Tensorflow log() method
- Python | os.abort() method
- Python | os.WEXITSTATUS() method
- Python | os._exit() method
- Python | iter() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


