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.
Output: 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
Output: After copying file:
['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp']
Destination path: /home/User/Desktop/file.txt
Output: 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