We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

The shutil module

This utility module contains some functions for copying files and directories. The copy function copies a file in pretty much the same way as the Unix cp command.

Example: Using the shutil module to copy files
# File: shutil-example-1.py

import shutil
import os

for file in os.listdir("."):
    if os.path.splitext(file)[1] == ".py":
        print file
        shutil.copy(file, os.path.join("backup", file))


The copytree function copies an entire directory tree (same as cp -r), and rmtree removes an entire tree (same as rm -r).

Example: 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

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