The shutil.copyfile()
method in Python is used to copy the contents of the source file to the target file. File metadata is not copied. Source and destination must represent a file, and destination must be writable. If the destination already exists, it will be replaced by the original file, otherwise a new file will be created.
If source and destination represent the same file, a 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: Using the shutil.copyfile () method to copy a file from the source to destination
|
Exit:
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 when using the shutil.copyfile () method
|
Output:
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: Processing errors when using the shutil.copyfile () method
|
Exit:
Destination is a directory.