Copy a directory recursively using Python (with examples)

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.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. Permissions and times of directories are copied with copystat() and individual files are copied using shutil.copy2().

Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)

Parameters:
src: A string representing the path of the source directory.
dest: A string representing the path of the destination.
symlinks (optional): This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.
ignore (optional): If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().
copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.
igonre_dangling_symlinks (optional): This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist.

Return Value: This method returns a string which represents the path of newly created directory.



Example: Suppose the directory looks like this.

python-shutil.copytree

We want to copy the folder ‘src‘ to a new folder ‘dst‘. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain shutil.copytree() method  
         
  
# importing shutil module  
import shutil  
     
# path  
path = 'D:/Pycharm projects/GeeksforGeeks/'  
     
# Source path  
src = 'D:/Pycharm projects/GeeksforGeeks/src'
     
# Destination path  
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
     
# Copy the content of  
# source to destination  
destination = shutil.copytree(src, dest)  
     
# print(destination) prints the
# path of newly created file 

chevron_right


Output:

python-shutil.copytree

Copy both file and directories

Tweaking the above code by a little bit allows us to copy both files or directories. This can be done using copytree() function and a try-except block. We will catch the exception and if the exception is ENOTDIR then we will use copy2() function to copy the files. Doing this allows us to copy both files and directories using a single code.

Let’s suppose the destination directory looks like this.

python-copy-files-and-directories



We want to copy a text file present in the src folder to this destination folder. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# shutil.copytree()
  
  
# Importing module
import shutil
import errno
  
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src/b/test_b.txt'
  
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
  
# Copy the content of
# source to destination
try:
    shutil.copytree(src, dest)
except OSError as err:
  
    # error caused if the source was not a directory
    if err.errno == errno.ENOTDIR:
        shutil.copy2(src, dest)
    else:
        print("Error: % s" % err)

chevron_right


Output:

python-copy-files-and-directories

Ignoring files and directories

Sometimes, while copying a directory to another directory, one may not want to copy the some files or sub-directories. Even this is handled by the shutil module. The function copytree() takes the argument ignore that allows specifying a function that returns a list of directories or files that should be ignored. This function takes the file or directory name as an argument which acts as a filter for names. If the argument passed is in names, then it is added to a list that specifies the copytree() which file or directory to skip.

Example: Suppose the source folder looks like this.

python-copy-files-and-directories

We want to copy the contents of above folder with the folder ‘a’. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# shutil.copytree()
  
  
# imporing modules
import shutil
  
# Declaring the ignore function
def ignoreFunc(file):
    def _ignore_(path, names):
          
        # List containing names of file 
        # that are needed to ignore
        ignored = []
          
        # check if file in names
        # then add it to list
        if file in names:
            ignored.append(file)
        return set(ignored)
          
    return _ignore_
      
  
# Source path  
src = 'D:/Pycharm projects /GeeksforGeeks/src'
  
# Destination path  
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
  
# Copying the contents from Source
# to Destination without some 
# specified files or directories
shutil.copytree(src, dest, ignore = ignoreFunc('a'))

chevron_right


Output:

python-copy-files-and-directories

To remove more than one file or a file with a paticular format, shutil.ignore_patterns is used. This function is passed as an argument to the copytree() method that specifies the glob patterns to filter out the files and directories.

Exmaple: We will use the above source folder as an example and will not copy any .txt file and folder ‘a’. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# shutil.copytree()
  
  
# importing modules
import shutil
  
# Source path  
src = 'D:/Pycharm projects/GeeksforGeeks/src'
  
# Destination path  
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
  
# Copying the contents from Source
# to Destination without some 
# specified files or directories
shutil.copytree(src, dest, ignore = shutil.ignore_patterns('*.txt', 'a'))

chevron_right


Output:

python-copy-files-and-directories

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.