Both of the copy scripts in the last section work as planned, but they aren’t very forgiving of existing directory trees. That is, they implicitly assume that the “to” target directory is either empty or doesn’t exist at all, and fail badly if that isn’t the case. Presumably, you will first somehow delete the target directory on your machine. For my purposes, that was a reasonable assumption to make.
The copiers could be changed to work with existing “to”
directories too (e.g., ignore
exceptions), but I prefer to start from scratch when copying trees;
you never know what old garbage might be laying around in the
“to” directory. So when testing the copies above, I was
careful to run a
cpexamples command line to recursively delete the
cpexamples directory tree before copying
another tree to that name.
Unfortunately, the rm command used to clear the target directory is really a Unix utility that I installed on my PC from a commercial package; it probably won’t work on your computer. There are other platform-specific ways to delete directory trees (e.g., deleting a folder’s icon in a Windows explorer GUI), but why not do it once in Python for every platform? Example 5-22 deletes every file and directory at and below a passed-in directory’s name. Because its logic is packaged as a function, it is also an importable utility that can be run from other scripts. Because it is pure Python code, it is a cross-platform solution for tree removal. ...