Debian Codegraph @

cpython27/Doc/library/shutil.rst

raw
1 :mod:`shutil` --- High-level file operations
2 ============================================
3
4 .. module:: shutil
5 :synopsis: High-level file operations, including copying.
6 .. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
7 .. partly based on the docstrings
8
9 .. index::
10 single: file; copying
11 single: copying files
12
13 **Source code:** :source:`Lib/shutil.py`
14
15 --------------
16
17 The :mod:`shutil` module offers a number of high-level operations on files and
18 collections of files. In particular, functions are provided which support file
19 copying and removal. For operations on individual files, see also the
20 :mod:`os` module.
21
22 .. warning::
23
24 Even the higher-level file copying functions (:func:`shutil.copy`,
25 :func:`shutil.copy2`) can't copy all file metadata.
26
27 On POSIX platforms, this means that file owner and group are lost as well
28 as ACLs. On Mac OS, the resource fork and other metadata are not used.
29 This means that resources will be lost and file type and creator codes will
30 not be correct. On Windows, file owners, ACLs and alternate data streams
31 are not copied.
32
33
34 .. _file-operations:
35
36 Directory and files operations
37 ------------------------------
38
39 .. function:: copyfileobj(fsrc, fdst[, length])
40
41 Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
42 The integer *length*, if given, is the buffer size. In particular, a negative
43 *length* value means to copy the data without looping over the source data in
44 chunks; by default the data is read in chunks to avoid uncontrolled memory
45 consumption. Note that if the current file position of the *fsrc* object is not
46 0, only the contents from the current file position to the end of the file will
47 be copied.
48
49
50 .. function:: copyfile(src, dst)
51
52 Copy the contents (no metadata) of the file named *src* to a file named
53 *dst*. *dst* must be the complete target file name; look at
54 :func:`shutil.copy` for a copy that accepts a target directory path. If
55 *src* and *dst* are the same files, :exc:`Error` is raised.
56 The destination location must be writable; otherwise, an :exc:`IOError` exception
57 will be raised. If *dst* already exists, it will be replaced. Special files
58 such as character or block devices and pipes cannot be copied with this
59 function. *src* and *dst* are path names given as strings.
60
61
62 .. function:: copymode(src, dst)
63
64 Copy the permission bits from *src* to *dst*. The file contents, owner, and
65 group are unaffected. *src* and *dst* are path names given as strings.
66
67
68 .. function:: copystat(src, dst)
69
70 Copy the permission bits, last access time, last modification time, and flags
71 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
72 and *dst* are path names given as strings.
73
74
75 .. function:: copy(src, dst)
76
77 Copy the file *src* to the file or directory *dst*. If *dst* is a directory, a
78 file with the same basename as *src* is created (or overwritten) in the
79 directory specified. Permission bits are copied. *src* and *dst* are path
80 names given as strings.
81
82
83 .. function:: copy2(src, dst)
84
85 Identical to :func:`~shutil.copy` except that :func:`copy2`
86 also attempts to preserve file metadata.
87
88 :func:`copy2` uses :func:`copystat` to copy the file metadata.
89 Please see :func:`copystat` for more information.
90
91
92 .. function:: ignore_patterns(\*patterns)
93
94 This factory function creates a function that can be used as a callable for
95 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
96 match one of the glob-style *patterns* provided. See the example below.
97
98 .. versionadded:: 2.6
99
100
101 .. function:: copytree(src, dst, symlinks=False, ignore=None)
102
103 Recursively copy an entire directory tree rooted at *src*. The destination
104 directory, named by *dst*, must not already exist; it will be created as
105 well as missing parent directories. Permissions and times of directories
106 are copied with :func:`copystat`, individual files are copied using
107 :func:`shutil.copy2`.
108
109 If *symlinks* is true, symbolic links in the source tree are represented as
110 symbolic links in the new tree, but the metadata of the original links is NOT
111 copied; if false or omitted, the contents and metadata of the linked files
112 are copied to the new tree.
113
114 If *ignore* is given, it must be a callable that will receive as its
115 arguments the directory being visited by :func:`copytree`, and a list of its
116 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
117 called recursively, the *ignore* callable will be called once for each
118 directory that is copied. The callable must return a sequence of directory
119 and file names relative to the current directory (i.e. a subset of the items
120 in its second argument); these names will then be ignored in the copy
121 process. :func:`ignore_patterns` can be used to create such a callable that
122 ignores names based on glob-style patterns.
123
124 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
125
126 The source code for this should be considered an example rather than the
127 ultimate tool.
128
129 .. versionchanged:: 2.3
130 :exc:`Error` is raised if any exceptions occur during copying, rather than
131 printing a message.
132
133 .. versionchanged:: 2.5
134 Create intermediate directories needed to create *dst*, rather than raising an
135 error. Copy permissions and times of directories using :func:`copystat`.
136
137 .. versionchanged:: 2.6
138 Added the *ignore* argument to be able to influence what is being copied.
139
140
141 .. function:: rmtree(path[, ignore_errors[, onerror]])
142
143 .. index:: single: directory; deleting
144
145 Delete an entire directory tree; *path* must point to a directory (but not a
146 symbolic link to a directory). If *ignore_errors* is true, errors resulting
147 from failed removals will be ignored; if false or omitted, such errors are
148 handled by calling a handler specified by *onerror* or, if that is omitted,
149 they raise an exception.
150
151 If *onerror* is provided, it must be a callable that accepts three
152 parameters: *function*, *path*, and *excinfo*. The first parameter,
153 *function*, is the function which raised the exception; it will be
154 :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
155 :func:`os.rmdir`. The second parameter, *path*, will be the path name passed
156 to *function*. The third parameter, *excinfo*, will be the exception
157 information return by :func:`sys.exc_info`. Exceptions raised by *onerror*
158 will not be caught.
159
160 .. versionchanged:: 2.6
161 Explicitly check for *path* being a symbolic link and raise :exc:`OSError`
162 in that case.
163
164
165 .. function:: move(src, dst)
166
167 Recursively move a file or directory (*src*) to another location (*dst*).
168
169 If the destination is an existing directory, then *src* is moved inside that
170 directory. If the destination already exists but is not a directory, it may
171 be overwritten depending on :func:`os.rename` semantics.
172
173 If the destination is on the current filesystem, then :func:`os.rename` is
174 used. Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
175 then removed.
176
177 .. versionadded:: 2.3
178
179
180 .. exception:: Error
181
182 This exception collects exceptions that are raised during a multi-file
183 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
184 (*srcname*, *dstname*, *exception*).
185
186 .. versionadded:: 2.3
187
188
189 .. _copytree-example:
190
191 copytree example
192 ::::::::::::::::
193
194 This example is the implementation of the :func:`copytree` function, described
195 above, with the docstring omitted. It demonstrates many of the other functions
196 provided by this module. ::
197
198 def copytree(src, dst, symlinks=False, ignore=None):
199 names = os.listdir(src)
200 if ignore is not None:
201 ignored_names = ignore(src, names)
202 else:
203 ignored_names = set()
204
205 os.makedirs(dst)
206 errors = []
207 for name in names:
208 if name in ignored_names:
209 continue
210 srcname = os.path.join(src, name)
211 dstname = os.path.join(dst, name)
212 try:
213 if symlinks and os.path.islink(srcname):
214 linkto = os.readlink(srcname)
215 os.symlink(linkto, dstname)
216 elif os.path.isdir(srcname):
217 copytree(srcname, dstname, symlinks, ignore)
218 else:
219 copy2(srcname, dstname)
220 # XXX What about devices, sockets etc.?
221 except (IOError, os.error) as why:
222 errors.append((srcname, dstname, str(why)))
223 # catch the Error from the recursive copytree so that we can
224 # continue with other files
225 except Error as err:
226 errors.extend(err.args[0])
227 try:
228 copystat(src, dst)
229 except WindowsError:
230 # can't copy file access times on Windows
231 pass
232 except OSError as why:
233 errors.extend((src, dst, str(why)))
234 if errors:
235 raise Error(errors)
236
237 Another example that uses the :func:`ignore_patterns` helper::
238
239 from shutil import copytree, ignore_patterns
240
241 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
242
243 This will copy everything except ``.pyc`` files and files or directories whose
244 name starts with ``tmp``.
245
246 Another example that uses the *ignore* argument to add a logging call::
247
248 from shutil import copytree
249 import logging
250
251 def _logpath(path, names):
252 logging.info('Working in %s' % path)
253 return [] # nothing will be ignored
254
255 copytree(source, destination, ignore=_logpath)
256
257
258 .. _archiving-operations:
259
260 Archiving operations
261 --------------------
262
263 High-level utilities to create and read compressed and archived files are also
264 provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
265
266 .. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
267
268 Create an archive file (eg. zip or tar) and returns its name.
269
270 *base_name* is the name of the file to create, including the path, minus
271 any format-specific extension. *format* is the archive format: one of
272 "zip" (if the :mod:`zlib` module or external ``zip`` executable is
273 available), "tar", "gztar" (if the :mod:`zlib` module is available), or
274 "bztar" (if the :mod:`bz2` module is available).
275
276 *root_dir* is a directory that will be the root directory of the
277 archive; ie. we typically chdir into *root_dir* before creating the
278 archive.
279
280 *base_dir* is the directory where we start archiving from;
281 ie. *base_dir* will be the common prefix of all files and
282 directories in the archive.
283
284 *root_dir* and *base_dir* both default to the current directory.
285
286 *owner* and *group* are used when creating a tar archive. By default,
287 uses the current owner and group.
288
289 *logger* must be an object compatible with :pep:`282`, usually an instance of
290 :class:`logging.Logger`.
291
292 .. versionadded:: 2.7
293
294
295 .. function:: get_archive_formats()
296
297 Return a list of supported formats for archiving.
298 Each element of the returned sequence is a tuple ``(name, description)``.
299
300 By default :mod:`shutil` provides these formats:
301
302 - *zip*: ZIP file (if the :mod:`zlib` module or external ``zip``
303 executable is available).
304 - *tar*: uncompressed tar file.
305 - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
306 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).
307
308 You can register new formats or provide your own archiver for any existing
309 formats, by using :func:`register_archive_format`.
310
311 .. versionadded:: 2.7
312
313
314 .. function:: register_archive_format(name, function, [extra_args, [description]])
315
316 Register an archiver for the format *name*. *function* is a callable that
317 will be used to invoke the archiver.
318
319 If given, *extra_args* is a sequence of ``(name, value)`` that will be
320 used as extra keywords arguments when the archiver callable is used.
321
322 *description* is used by :func:`get_archive_formats` which returns the
323 list of archivers. Defaults to an empty list.
324
325 .. versionadded:: 2.7
326
327
328 .. function:: unregister_archive_format(name)
329
330 Remove the archive format *name* from the list of supported formats.
331
332 .. versionadded:: 2.7
333
334
335 .. _archiving-example:
336
337 Archiving example
338 :::::::::::::::::
339
340 In this example, we create a gzip'ed tar-file archive containing all files
341 found in the :file:`.ssh` directory of the user::
342
343 >>> from shutil import make_archive
344 >>> import os
345 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
346 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
347 >>> make_archive(archive_name, 'gztar', root_dir)
348 '/Users/tarek/myarchive.tar.gz'
349
350 The resulting archive contains:
351
352 .. code-block:: shell-session
353
354 $ tar -tzvf /Users/tarek/myarchive.tar.gz
355 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
356 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
357 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
358 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
359 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
360 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
361 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
362 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts