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