Copy a directory recursively using Python (with examples)
Last Updated :
20 Jul, 2021
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, ignore_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.
ignore_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.

We want to copy the folder ‘src’ to a new folder ‘dst’. Below is the implementation.
Python3
import shutil
path = 'D:/Pycharm projects/GeeksforGeeks/'
src = 'D:/Pycharm projects/GeeksforGeeks/src'
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
destination = shutil.copytree(src, dest)
|
Output:

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.

We want to copy a text file present in the src folder to this destination folder. Below is the implementation.
Python3
import shutil
import errno
src = 'D:/Pycharm projects/GeeksforGeeks/src/b/test_b.txt'
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
try :
shutil.copytree(src, dest)
except OSError as err:
if err.errno = = errno.ENOTDIR:
shutil.copy2(src, dest)
else :
print ( "Error: % s" % err)
|
Output:

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.

We want to copy the contents of above folder with the folder ‘a’. Below is the implementation.
Python3
import shutil
def ignoreFunc( file ):
def _ignore_(path, names):
ignored = []
if file in names:
ignored.append( file )
return set (ignored)
return _ignore_
src = 'D:/Pycharm projects /GeeksforGeeks/src'
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
shutil.copytree(src, dest, ignore = ignoreFunc( 'a' ))
|
Output:

To remove more than one file or a file with a particular 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.
Example: We will use the above source folder as an example and will not copy any .txt file and folder ‘a’. Below is the implementation.
Python3
import shutil
src = 'D:/Pycharm projects/GeeksforGeeks/src'
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
shutil.copytree(src, dest, ignore = shutil.ignore_patterns( '*.txt' , 'a' ))
|
Output:

Similar Reads
Python - Copy Directory Structure Without Files
In this article, we will discuss how to copy the directory structure with files using Python. For example, consider this directory tree: We have a folder named "base" and inside have we have one folder named "Structure". "Structure" has some folders inside which also contain some files. Now we have
3 min read
How to print all files within a directory using Python?
The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to
3 min read
Copy all files from one directory to another using Python
Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Letâs explore various methods to do this efficiently. Us
2 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__S
3 min read
Check if directory contains files using python
Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(
3 min read
Finding the largest file in a directory using Python
In this article, we will find the file having the largest size in a given directory using Python. We will check all files in the main directory and each of its subdirectories. Modules required: os: The os module in Python provides a way of using operating system dependent functionality. OS module is
2 min read
Delete an entire directory tree using Python | shutil.rmtree() method
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 the process of copying and removal of files and directories. shutil.rmtree() is used to delete an entire direc
3 min read
List all files of certain type in a directory using Python
In python, there are several built-in modules and methods for file handling. These functions are present in different modules such as os, glob, etc. This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type
3 min read
Python - Get list of files in directory with size
In this article, we are going to see how to extract the list of files of the directory along with its size. For this, we will use the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a
9 min read
Getting all CSV files from a directory using Python
Python provides many inbuilt packages and modules to work with CSV files in the workspace. The CSV files can be accessed within a system's directories and subdirectories and modified or edited. The CSV file contents can both be printed on the shell, or it can be saved in the form of the dataframe an
3 min read