The shutil
utility module contains some functions for copying files and
directories. The copy
function used in Example 2-4 copies a file in
pretty much the same way as the Unix cp
command.
The copytree
function copies an entire directory
tree (same as cp
-r
), and rmtree
removes an entire tree (same as rm
-r
). These functions are illustrated in Example 2-5.
Example 2-5. Using the shutil Module to Copy and Remove Directory Trees
File: shutil-example-2.py import shutil import os SOURCE = "samples" BACKUP = "samples-bak" # create a backup directory shutil.copytree(SOURCE, BACKUP) print os.listdir(BACKUP) # remove it shutil.rmtree(BACKUP) print os.listdir(BACKUP)['sample.wav', 'sample.jpg', 'sample.au', 'sample.msg', 'sample.tgz',
...
Traceback (most recent call last):
File "shutil-example-2.py", line 17, in ?
print os.listdir(BACKUP)
os.error: No such file or directory
3.147.84.157