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 to copy all the folders of “Structure” to a folder named “copied_structure” such that files are not copied.
In this article, we will discuss various ways to do it.
- Using shutil.copytree()
- Using os.walk()
Method 1: Using shutil.copytree()
Using the shutil.copytree() method of shutil library we can achieve this task. 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. It takes an optional argument which is “ignore”. 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(). For better understanding let’s implement this method by writing code.
The code to copy only directory structure of “Structure” without file to “copied_structure” will be:
After running above the code we will find that a new folder named “copied_structure” is made which contains the same folder structure as the “Structure” folder but does not have any file present in the “Structure” folder.
Method 2: Using os.walk()
We can also achieve the above task by using the os.walk() method of os module. We will do this by walking to every directory of the source directory and getting the folder names and their relative path from the source directory and then by this relative path, we will make a copy of them in the destination directory using os.mkdir(). The code for this implementation is:
After running this code we will find that a folder named “copied_structure” is made which has the same directory structure as “Structure” but has no file in it.