Search code examples
pythondirectorysubdirectoryshutilpathlib

Python - Create a subdirectory contains all directories and files in the parent directory


I want to create a subdirectory contains all directories and files in the parent directory.

For example: There exists a parent directory and its subdirectories and files.

/parent
    /parent/child1
        /parent/child1/a.txt
        /parent/child1/b.txt
    /parent/child2
        /parent/child2/child2-1
            /parent/child2/child2-1/c.txt
        /parent/child2/child2/d.txt
    /parent/e.txt

My Target: Create a subdirectory called "new" that contains all directories and files in the parent directory.:

/parent
    /parent/new
        /parent/new/child1
            /parent/new/child1/a.txt
            /parent/new/child1/b.txt
        /parent/new/child2
            /parent/new/child2/child2-1
                /parent/new/child2/child2-1/c.txt
            /parent/new/child2/child2/d.txt
        /parent/new/e.txt

Is there a Pythonic way to meet my needs?

Thanks!


Solution

  • shutil.copytree is the usual way to recursively copy a directory tree to a new location, and it has options for whether to error out on existing directories, follow symlinks, and so on.

    The complication, however, is that your destination is inside of the source, meaning that any recursive approach may end up beginning to re-copy the newly created tree as part of the source, ad infinitum.

    The safest way to manage this is to copy your directory of interest to some temporary directory outside of it, and then copy from that intermediate location to the destination:

    import tempfile, shutil
    with tempfile.TemporaryDirectory() as temp:
        temp_new = temp + '/new'
        shutil.copytree('..', temp_new)
        shutil.copytree(temp_new, 'new')