Making copies of a directory's contents is something we can do easily, but what if I told you that a tool such as cp
(the command to copy files on GNU systems) is around 1,200 lines of code?
Obviously, the cp
implementation is not Python-based, it has evolved over decades, and it takes care of far more than you probably need, but still rolling your own code to copy a directory recursively takes far more than you would expect.
Luckily for us, the Python standard library provides utilities to perform the most common operations out of the box and this is one of them.
The steps for this recipe are as follows:
- The
copydir
function can rely onshutil.copytree
to do most of the work:
import shutil def copydir(source, dest, ignore=None): """Copy source to dest and ignore any file matching ignore pattern.""" shutil.copytree(source, dest, ignore_dangling_symlinks=True, ignore=shutil.ignore_patterns(*ignore) if ...