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