How to use shutil.copyfile() method in Python

Here we learn How to use shutil.copyfile() methods in Python.

shutil.copyfile()  Method

The Python Shutil module provides many high-end file copies and deletes functions. These features provide an efficient way to copy files and save time performing unnecessary file open, read, write, and close tasks. Familiarize yourself with Python’s module. Describes how to perform high-level file operations such as B. Create a new copy file, archive it, and use a Python script to copy the content from one file to another. Let’s give a basic introduction to the Shutil module.  The source and target must be files, and the target must be writable.

In the syntax –

  • The first argument is the source, which specifies the path to the source file.
  • The second argument is the target, the path to the target file.
  • The third argument is optional. The default value of this parameter is true.
  • Returns a string giving the path of the newly created file.

Check Example:-

  • We will use this copy file method to copy a file from the source to the destination file.
       # How to use shutil.copyfile() method in Python

import os
import shutil
path = '/User/Document'

# The all List files and directory
print("Before copying:")

# Source path
src = "/User/Document/new_file.txt"         # src= Source
des = "/User/Document/new_file_copy.txt"    # des= Destination
dest = shutil.copyfile(src, des)

print("After copying both files:")
print("New Destination path:", dest)


Before copying :
['Photo.png', 'new.txt', 'file1.text', 'copy_1.cpp']
After copying both files:
['Photo.png','new.txt', 'file1.text', 'file(copy).txt', 'copy_1.cpp']
New Destination path: /User/Documents/file(copy).txt


For more information, use the following link to learn how to use shutil.copyfile() the method in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *