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