The Wayback Machine - https://web.archive.org/web/20240715172931/https://www.geeksforgeeks.org/python-copy-directory-structure-without-files/
Open In App

Python – Copy Directory Structure Without Files

Last Updated : 27 Dec, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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




# importing the shutil module
import shutil
 
# importing the os module
import os
 
# defining the function to ignore the files
# if present in any folder
def ignore_files(dir, files):
    return [f for f in files if os.path.isfile(os.path.join(dir, f))]
 
# calling the shutil.copytree() method and
# passing the src,dst,and ignore parameter
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




# importing the os module
import os
 
# defining a function for the task
def create_dirtree_without_files(src, dst):
   
      # getting the absolute path of the source
    # directory
    src = os.path.abspath(src)
     
    # making a variable having the index till which
    # src string has directory and a path separator
    src_prefix = len(src) + len(os.path.sep)
     
    # making the destination directory
    os.makedirs(dst)
     
    # doing os walk in source directory
    for root, dirs, files in os.walk(src):
        for dirname in dirs:
           
            # here dst has destination directory,
            # root[src_prefix:] gives us relative
            # path from source directory
            # and dirname has folder names
            dirpath = os.path.join(dst, root[src_prefix:], dirname)
             
            # making the path which we made by
            # joining all of the above three
            os.mkdir(dirpath)
 
# calling the above function
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. 

 



Similar Reads

Copy all files from one directory to another using Python
In this article, we will discuss how to copy all files from one directory to another using Python. This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories. Method 1 : Using shut
2 min read
copy in Python (Deep Copy and Shallow Copy)
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create "real copies" or "clones" of these objects, we can use the copy module in Python. Syntax of Python DeepcopySyntax:
5 min read
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 desti
5 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 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(<directory path>) Returns: A list of files pr
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 in a directory by using Python programming. So the
3 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 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 and played with later. In this article, we will see
3 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir() functionUsing glob() functions Method 1: Using o
3 min read
Python - List files in directory with extension
In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python. Modules Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pa
3 min read
Practice Tags :
three90RightbarBannerImg