The shutil Module

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.

Example 2-4. Using the shutil Module to Copy Files


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). These functions are illustrated in Example 2-5.

Example 2-5. Using the shutil Module to Copy and Remove Directory Trees


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.msg', 'sample.tgz',
Traceback (most recent call last):
 File "", line 17, in ?
 print os.listdir(BACKUP)
os.error: No such file or directory

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: