In this article we will discuss how to copy files from one directory to another using shutil.copy().

shutil.copy()

Python’s shutil module provides a function shutil.copy() i.e.

It copies the file pointed by src to the directory pointed by dst.

Parameters:

  • src is the file path in string
  • dst can be a directory path or another file path in string.
  • If src is a path of symbolic link,
    • If follow_symlinks is True, then it will copy the file pointed by symbolic link.
    • If follow_symlinks is False, then it create a new similar symbolic link in dst directory.

Returns :

  • It returns the path string of the newly created file.

Module Required,

Let’s use this function to copy files,

Copy a file to other Directory

It will copy the file ‘sample1.txt’ to the directory ‘/home/varung/test’ and returns the path of newly created file i.e.

Some Important Points:

  • If Destination directory already has a file with same name then it will be overwritten.
  • If there is no directory with name test inside /home/varung then it will copy the source file inside /home/varun with name test.
  • If the destination path is not valid i.e. any intermediate directory does not exist then it will give error i.e.
    • FileNotFoundError: [Errno 2] No such file or directory: 

Copy a File to other directory with new name

It will copy the file file sample1.txt to another location with name sample2.txt.

Some Important Points:

  • If Destination file already exists then it will be overwritten.
  • If the destination path is not valid i.e. any intermediate directory does not exist then it will give error i.e.
    • FileNotFoundError: [Errno 2] No such file or directory: 

Copy symbolic links using shutil.copy()

Suppose we a symbolic link link.csv that points to sample.csv i.e.

Let’s copy symbolic link using shutil.copy() i.e.

By default follow_symlinks is True i.e. it will copy the target file pointed by source link to the destination director.

Contents of newPath will be,

sample2.csv is not a link but actual copy of sample1.csv ( file pointed by link.csv)

If follow_symlinks is False i.e.

It will copy the symbolic link i.e. newlink.csv will be a link pointing to same target file sample1.csv i.e.
newlink.csv -> sample1.txt

If symbolic link is broken i.e. target file doesn’t exists then it will give error,
FileNotFoundError: [Errno 2] No such file or directory

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.