Python – Copy Directory Structure Without Files
Last Updated :
27 Dec, 2021
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:
Python
import shutil
import os
def ignore_files( dir , files):
return [f for f in files if os.path.isfile(os.path.join( dir , f))]
shutil.copytree( 'D:/projects/base/Structure' ,
'D:/projects/base/copied_structure' ,
ignore = ignore_files)
|
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:
Python
import os
def create_dirtree_without_files(src, dst):
src = os.path.abspath(src)
src_prefix = len (src) + len (os.path.sep)
os.makedirs(dst)
for root, dirs, files in os.walk(src):
for dirname in dirs:
dirpath = os.path.join(dst, root[src_prefix:], dirname)
os.mkdir(dirpath)
create_dirtree_without_files( 'D:/projects/base/Structure' ,
'D:/projects/base/copied_structure' )
|
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.
Share your thoughts in the comments
Please Login to comment...