blob: 7ed70af68a3fbc0c3f0f603d0ca4b0bf4262743b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`shutil` --- High-level file operations
3============================================
4
5.. module:: shutil
6 :synopsis: High-level file operations, including copying.
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8
9
10.. % partly based on the docstrings
11
12.. index::
13 single: file; copying
14 single: copying files
15
16The :mod:`shutil` module offers a number of high-level operations on files and
17collections of files. In particular, functions are provided which support file
18copying and removal.
19
20**Caveat:** On MacOS, the resource fork and other metadata are not used. For
21file copies, this means that resources will be lost and file type and creator
22codes will not be correct.
23
24
25.. function:: copyfile(src, dst)
26
27 Copy the contents of the file named *src* to a file named *dst*. The
28 destination location must be writable; otherwise, an :exc:`IOError` exception
29 will be raised. If *dst* already exists, it will be replaced. Special files
30 such as character or block devices and pipes cannot be copied with this
31 function. *src* and *dst* are path names given as strings.
32
33
34.. function:: copyfileobj(fsrc, fdst[, length])
35
36 Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
37 The integer *length*, if given, is the buffer size. In particular, a negative
38 *length* value means to copy the data without looping over the source data in
39 chunks; by default the data is read in chunks to avoid uncontrolled memory
40 consumption. Note that if the current file position of the *fsrc* object is not
41 0, only the contents from the current file position to the end of the file will
42 be copied.
43
44
45.. function:: copymode(src, dst)
46
47 Copy the permission bits from *src* to *dst*. The file contents, owner, and
48 group are unaffected. *src* and *dst* are path names given as strings.
49
50
51.. function:: copystat(src, dst)
52
53 Copy the permission bits, last access time, last modification time, and flags
54 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
55 and *dst* are path names given as strings.
56
57
58.. function:: copy(src, dst)
59
60 Copy the file *src* to the file or directory *dst*. If *dst* is a directory, a
61 file with the same basename as *src* is created (or overwritten) in the
62 directory specified. Permission bits are copied. *src* and *dst* are path
63 names given as strings.
64
65
66.. function:: copy2(src, dst)
67
68 Similar to :func:`copy`, but last access time and last modification time are
69 copied as well. This is similar to the Unix command :program:`cp -p`.
70
71
72.. function:: copytree(src, dst[, symlinks])
73
74 Recursively copy an entire directory tree rooted at *src*. The destination
75 directory, named by *dst*, must not already exist; it will be created as well as
76 missing parent directories. Permissions and times of directories are copied with
77 :func:`copystat`, individual files are copied using :func:`copy2`. If
78 *symlinks* is true, symbolic links in the source tree are represented as
79 symbolic links in the new tree; if false or omitted, the contents of the linked
80 files are copied to the new tree. If exception(s) occur, an :exc:`Error` is
81 raised with a list of reasons.
82
83 The source code for this should be considered an example rather than a tool.
84
85 .. versionchanged:: 2.3
86 :exc:`Error` is raised if any exceptions occur during copying, rather than
87 printing a message.
88
89 .. versionchanged:: 2.5
90 Create intermediate directories needed to create *dst*, rather than raising an
91 error. Copy permissions and times of directories using :func:`copystat`.
92
93
94.. function:: rmtree(path[, ignore_errors[, onerror]])
95
96 .. index:: single: directory; deleting
97
98 Delete an entire directory tree (*path* must point to a directory). If
99 *ignore_errors* is true, errors resulting from failed removals will be ignored;
100 if false or omitted, such errors are handled by calling a handler specified by
101 *onerror* or, if that is omitted, they raise an exception.
102
103 If *onerror* is provided, it must be a callable that accepts three parameters:
104 *function*, *path*, and *excinfo*. The first parameter, *function*, is the
105 function which raised the exception; it will be :func:`os.listdir`,
106 :func:`os.remove` or :func:`os.rmdir`. The second parameter, *path*, will be
107 the path name passed to *function*. The third parameter, *excinfo*, will be the
108 exception information return by :func:`sys.exc_info`. Exceptions raised by
109 *onerror* will not be caught.
110
111
112.. function:: move(src, dst)
113
114 Recursively move a file or directory to another location.
115
116 If the destination is on our current filesystem, then simply use rename.
117 Otherwise, copy src to the dst and then remove src.
118
119 .. versionadded:: 2.3
120
121
122.. exception:: Error
123
124 This exception collects exceptions that raised during a mult-file operation. For
125 :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*,
126 *dstname*, *exception*).
127
128 .. versionadded:: 2.3
129
130
131.. _shutil-example:
132
133Example
134-------
135
136This example is the implementation of the :func:`copytree` function, described
137above, with the docstring omitted. It demonstrates many of the other functions
138provided by this module. ::
139
140 def copytree(src, dst, symlinks=False):
141 names = os.listdir(src)
142 os.makedirs(dst)
143 errors = []
144 for name in names:
145 srcname = os.path.join(src, name)
146 dstname = os.path.join(dst, name)
147 try:
148 if symlinks and os.path.islink(srcname):
149 linkto = os.readlink(srcname)
150 os.symlink(linkto, dstname)
151 elif os.path.isdir(srcname):
152 copytree(srcname, dstname, symlinks)
153 else:
154 copy2(srcname, dstname)
155 # XXX What about devices, sockets etc.?
156 except (IOError, os.error), why:
157 errors.append((srcname, dstname, str(why)))
158 # catch the Error from the recursive copytree so that we can
159 # continue with other files
160 except Error, err:
161 errors.extend(err.args[0])
162 try:
163 copystat(src, dst)
164 except WindowsError:
165 # can't copy file access times on Windows
166 pass
167 except OSError, why:
168 errors.extend((src, dst, str(why)))
169 if errors:
170 raise Error, errors