blob: 7cf8550d473cb5ce3eef0bd8355ad2bbc8d91c69 [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>
Christian Heimes5b5e81c2007-12-31 16:14:33 +00008.. partly based on the docstrings
Georg Brandl116aa622007-08-15 14:28:22 +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
Guido van Rossum2cc30da2007-11-02 23:46:40 +000016copying and removal. For operations on individual files, see also the
17:mod:`os` module.
Georg Brandl116aa622007-08-15 14:28:22 +000018
Guido van Rossumda27fd22007-08-17 00:24:54 +000019.. warning::
Christian Heimes7f044312008-01-06 17:05:40 +000020
21 Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
22 can't copy all file metadata.
Georg Brandl48310cd2009-01-03 21:18:54 +000023
Christian Heimes7f044312008-01-06 17:05:40 +000024 On POSIX platforms, this means that file owner and group are lost as well
Georg Brandlc575c902008-09-13 17:46:05 +000025 as ACLs. On Mac OS, the resource fork and other metadata are not used.
Christian Heimes7f044312008-01-06 17:05:40 +000026 This means that resources will be lost and file type and creator codes will
27 not be correct. On Windows, file owners, ACLs and alternate data streams
28 are not copied.
Georg Brandl116aa622007-08-15 14:28:22 +000029
30
Georg Brandl116aa622007-08-15 14:28:22 +000031.. function:: copyfileobj(fsrc, fdst[, length])
32
33 Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
34 The integer *length*, if given, is the buffer size. In particular, a negative
35 *length* value means to copy the data without looping over the source data in
36 chunks; by default the data is read in chunks to avoid uncontrolled memory
37 consumption. Note that if the current file position of the *fsrc* object is not
38 0, only the contents from the current file position to the end of the file will
39 be copied.
40
41
Christian Heimesa342c012008-04-20 21:01:16 +000042.. function:: copyfile(src, dst)
43
44 Copy the contents (no metadata) of the file named *src* to a file named *dst*.
45 *dst* must be the complete target file name; look at :func:`copy` for a copy that
Georg Brandlaf265f42008-12-07 15:06:20 +000046 accepts a target directory path. If *src* and *dst* are the same files,
47 :exc:`Error` is raised.
Christian Heimesa342c012008-04-20 21:01:16 +000048 The destination location must be writable; otherwise, an :exc:`IOError` exception
49 will be raised. If *dst* already exists, it will be replaced. Special files
50 such as character or block devices and pipes cannot be copied with this
51 function. *src* and *dst* are path names given as strings.
52
53
Georg Brandl116aa622007-08-15 14:28:22 +000054.. function:: copymode(src, dst)
55
56 Copy the permission bits from *src* to *dst*. The file contents, owner, and
57 group are unaffected. *src* and *dst* are path names given as strings.
58
59
60.. function:: copystat(src, dst)
61
62 Copy the permission bits, last access time, last modification time, and flags
63 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
64 and *dst* are path names given as strings.
65
66
67.. function:: copy(src, dst)
68
69 Copy the file *src* to the file or directory *dst*. If *dst* is a directory, a
70 file with the same basename as *src* is created (or overwritten) in the
71 directory specified. Permission bits are copied. *src* and *dst* are path
72 names given as strings.
73
74
75.. function:: copy2(src, dst)
76
Alexandre Vassalottibee32532008-05-16 18:15:12 +000077 Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just
78 :func:`copy` followed by :func:`copystat`. This is similar to the
79 Unix command :program:`cp -p`.
Georg Brandl116aa622007-08-15 14:28:22 +000080
81
Georg Brandl86b2fb92008-07-16 03:43:04 +000082.. function:: ignore_patterns(\*patterns)
83
84 This factory function creates a function that can be used as a callable for
85 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
86 match one of the glob-style *patterns* provided. See the example below.
87
88
89.. function:: copytree(src, dst[, symlinks=False[, ignore=None]])
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 Recursively copy an entire directory tree rooted at *src*. The destination
Georg Brandl86b2fb92008-07-16 03:43:04 +000092 directory, named by *dst*, must not already exist; it will be created as well
93 as missing parent directories. Permissions and times of directories are
94 copied with :func:`copystat`, individual files are copied using
95 :func:`copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +000096
Georg Brandl86b2fb92008-07-16 03:43:04 +000097 If *symlinks* is true, symbolic links in the source tree are represented as
98 symbolic links in the new tree; if false or omitted, the contents of the
99 linked files are copied to the new tree.
100
101 If *ignore* is given, it must be a callable that will receive as its
102 arguments the directory being visited by :func:`copytree`, and a list of its
103 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
104 called recursively, the *ignore* callable will be called once for each
105 directory that is copied. The callable must return a sequence of directory
106 and file names relative to the current directory (i.e. a subset of the items
107 in its second argument); these names will then be ignored in the copy
108 process. :func:`ignore_patterns` can be used to create such a callable that
109 ignores names based on glob-style patterns.
110
111 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
112
113 The source code for this should be considered an example rather than the
114 ultimate tool.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116
117.. function:: rmtree(path[, ignore_errors[, onerror]])
118
119 .. index:: single: directory; deleting
120
Christian Heimes9bd667a2008-01-20 15:14:11 +0000121 Delete an entire directory tree; *path* must point to a directory (but not a
122 symbolic link to a directory). If *ignore_errors* is true, errors resulting
123 from failed removals will be ignored; if false or omitted, such errors are
124 handled by calling a handler specified by *onerror* or, if that is omitted,
125 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Christian Heimes9bd667a2008-01-20 15:14:11 +0000127 If *onerror* is provided, it must be a callable that accepts three
128 parameters: *function*, *path*, and *excinfo*. The first parameter,
129 *function*, is the function which raised the exception; it will be
130 :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
131 :func:`os.rmdir`. The second parameter, *path*, will be the path name passed
132 to *function*. The third parameter, *excinfo*, will be the exception
133 information return by :func:`sys.exc_info`. Exceptions raised by *onerror*
134 will not be caught.
135
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137.. function:: move(src, dst)
138
139 Recursively move a file or directory to another location.
140
Christian Heimes7f044312008-01-06 17:05:40 +0000141 If the destination is on the current filesystem, then simply use rename.
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000142 Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145.. exception:: Error
146
Christian Heimes7f044312008-01-06 17:05:40 +0000147 This exception collects exceptions that raised during a multi-file operation. For
Georg Brandl116aa622007-08-15 14:28:22 +0000148 :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*,
149 *dstname*, *exception*).
150
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152.. _shutil-example:
153
154Example
155-------
156
157This example is the implementation of the :func:`copytree` function, described
158above, with the docstring omitted. It demonstrates many of the other functions
159provided by this module. ::
160
161 def copytree(src, dst, symlinks=False):
162 names = os.listdir(src)
163 os.makedirs(dst)
164 errors = []
165 for name in names:
166 srcname = os.path.join(src, name)
167 dstname = os.path.join(dst, name)
168 try:
169 if symlinks and os.path.islink(srcname):
170 linkto = os.readlink(srcname)
171 os.symlink(linkto, dstname)
172 elif os.path.isdir(srcname):
173 copytree(srcname, dstname, symlinks)
174 else:
175 copy2(srcname, dstname)
176 # XXX What about devices, sockets etc.?
177 except (IOError, os.error) as why:
178 errors.append((srcname, dstname, str(why)))
179 # catch the Error from the recursive copytree so that we can
180 # continue with other files
181 except Error as err:
182 errors.extend(err.args[0])
183 try:
184 copystat(src, dst)
185 except WindowsError:
186 # can't copy file access times on Windows
187 pass
188 except OSError as why:
189 errors.extend((src, dst, str(why)))
190 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000191 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000192