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
?
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:
Find shutil.py
on your system and open in a text editor/IDE.
Find the line that says:
def copytree(src, dst, symlinks=False, ignore=None):
Copy everything from here to the end of the copytree
function.
Then paste this into your code and rename to something like def moveWithIgnore(src, ...
or move2(..)
.
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 :-)