pythonshutil

How do you move a file system tree with ignore patterns?


With shutil.copytree I can copy an entire directory with files and folders into a folder within itself and at the same time ignore certain folders and their content.

source = htpc.root
destination = os.path.join(htpc.root, "old")

shutil.copytree(source, destination, ignore=shutil.ignore_patterns('userdata', 'old'))

Is there a way to do this exact same thing, except move and not copy, so I'll only be left with userdata and old in the root directory with all the old files and folders within old?


Solution

  • As of Python 2.6, The shutil module does not provide that function.

    You can see the the copytree() function, and others, in the file: shutil.py.

    Perhaps located at: /usr/local/python2.6/shutil.py

    There are 9 functions, shutil pydoc.

    Because copytree is so close to what you need already, I would approach this by cloning it to a new function and then tweaking it to move rather than copy.

    To do this:

    The comments at the top of the original copytree() function say copy2() does the 'work'. In shutils.py you can see it takes (src, dst) as arguments.

    Also in shutils is the move() function, which also takes (src, dst). It looks like it is safe to swap copy2 for move in the new moveWithIgnore function.

    The original copytree() function uses recursion (it calls itself). Be sure to update the line of code in the new function so it calls itself rather than copytree.

    I'm sure you can take it from here :-)