In python, how can I make an exact copy of a folder tree without the files?

835 views Asked by At

I need to make a copy of a folder with all of its subfolders, but do it without any of the files coming with the directories.

In Python, I am using the os.walk function to go top-down in a directory to process lots of images in lots of sub-folders. I want to make an exact copy of this folder tree (that the os.walk function goes through) and have it in a different directory I specify. This is to allow me to save my output images in the equivalent copy of the folder they came from.

I tried:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

but have no clue how to edit it to what I want. How can I use a python command to copy an empty folder-tree to a directory I choose?

Should I use the shutil.copytree command or should I put something inside the for loop processing the images or something else?

1

There are 1 answers

1
gelonida On

You could use shutil.copytree if you want to:

It has an ignore parameter, that will allow you to ignore items from being copied (in your case ignore all non directories)

import os
import shutil

def cptree(src, dst):

    def keep_only_dirs(path, files):
        to_ignore = [
            fname for fname in files
            if not os.path.isdir(os.path.join(path, fname))
            ]
        return to_ignore

    # This works for python3 (<3.8), BUT the target directory MUST not exist
    shutil.copytree(src, dst, ignore=keep_only_dirs)

    # For python 3.8 you can use following code (Here the target directory can
    # already exist and only new directories will be added
    # shutil.copytree(src, dst, ignore=keep_only_dirs, dirs_exist_ok=True)

Alternatively if you don't have python3.8 and you want to be able to make the code working with an existing target directory, you could handcraft some code using os.walk()

If this is what you need tell me and I'll write an example.