rest25/library/shutil.rst => rest262/library/shutil.rst
f1
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>
n8- 
9- 
10-.. % partly based on the docstrings
8+.. 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
n18-copying and removal.
n16+copying and removal. For operations on individual files, see also the
17+:mod:`os` module.
19
n19+.. warning::
20+ 
21+   Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
22+   can't copy all file metadata.
23+ 
24+   On POSIX platforms, this means that file owner and group are lost as well
20-**Caveat:**  On MacOS, the resource fork and other metadata are not used.  For
25+   as ACLs.  On Mac OS, the resource fork and other metadata are not used.
21-file copies, this means that resources will be lost and  file type and creator
26+   This means that resources will be lost and file type and creator codes will
22-codes will not be correct.
27+   not be correct. On Windows, file owners, ACLs and alternate data streams
23- 
28+   are not copied.
24- 
25-.. function:: copyfile(src, dst)
26- 
27-   Copy the contents of the file named *src* to a file named *dst*.  The
28-   destination location must be writable; otherwise,  an :exc:`IOError` exception
29-   will be raised. If *dst* already exists, it will be replaced.   Special files
30-   such as character or block devices and pipes cannot be copied with this
31-   function.  *src* and *dst* are path names given as strings.
32
33
34.. function:: copyfileobj(fsrc, fdst[, length])
35
36   Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
37   The integer *length*, if given, is the buffer size. In particular, a negative
38   *length* value means to copy the data without looping over the source data in
39   chunks; by default the data is read in chunks to avoid uncontrolled memory
n40-   consumption.
n37+   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+ 
42+.. 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
46+   accepts a target directory path.  If *src* and *dst* are the same files,
47+   :exc:`Error` is raised.
48+   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.
41
42
43.. function:: copymode(src, dst)
44
45   Copy the permission bits from *src* to *dst*.  The file contents, owner, and
46   group are unaffected.  *src* and *dst* are path names given as strings.
47
48
49.. function:: copystat(src, dst)
50
n51-   Copy the permission bits, last access time, and last modification time from
n62+   Copy the permission bits, last access time, last modification time, and flags
52-   *src* to *dst*.  The file contents, owner, and group are unaffected.  *src* and
63+   from *src* to *dst*.  The file contents, owner, and group are unaffected.  *src*
53-   *dst* are path names given as strings.
64+   and *dst* are path names given as strings.
54
55
56.. function:: copy(src, dst)
57
58   Copy the file *src* to the file or directory *dst*.  If *dst* is a directory, a
59   file with the same basename as *src*  is created (or overwritten) in the
60   directory specified.  Permission bits are copied.  *src* and *dst* are path
61   names given as strings.
62
63
64.. function:: copy2(src, dst)
65
n66-   Similar to :func:`copy`, but last access time and last modification time are
n77+   Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just
67-   copied as well.  This is similar to the Unix command :program:`cp` :option:`-p`.
78+   :func:`copy` followed by :func:`copystat`.  This is similar to the
79+   Unix command :program:`cp -p`.
68
69
n82+.. 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+   .. versionadded:: 2.6
89+ 
90+ 
70-.. function:: copytree(src, dst[, symlinks])
91+.. function:: copytree(src, dst[, symlinks=False[, ignore=None]])
71
72   Recursively copy an entire directory tree rooted at *src*.  The destination
n73-   directory, named by *dst*, must not already exist; it will be created as well as
n94+   directory, named by *dst*, must not already exist; it will be created as well
74-   missing parent directories. Permissions and times of directories are copied with
95+   as missing parent directories.  Permissions and times of directories are
75-   :func:`copystat`, individual files are copied using :func:`copy2`.   If
96+   copied with :func:`copystat`, individual files are copied using
97+   :func:`copy2`.
98+ 
76-   *symlinks* is true, symbolic links in the source tree are represented as
99+   If *symlinks* is true, symbolic links in the source tree are represented as
77-   symbolic links in the new tree; if false or omitted, the contents of the linked
100+   symbolic links in the new tree; if false or omitted, the contents of the
78-   files are copied to the new tree.  If exception(s) occur, an :exc:`Error` is
101+   linked files are copied to the new tree.
79-   raised with a list of reasons.
80
n103+   If *ignore* is given, it must be a callable that will receive as its
104+   arguments the directory being visited by :func:`copytree`, and a list of its
105+   contents, as returned by :func:`os.listdir`.  Since :func:`copytree` is
106+   called recursively, the *ignore* callable will be called once for each
107+   directory that is copied.  The callable must return a sequence of directory
108+   and file names relative to the current directory (i.e. a subset of the items
109+   in its second argument); these names will then be ignored in the copy
110+   process.  :func:`ignore_patterns` can be used to create such a callable that
111+   ignores names based on glob-style patterns.
112+ 
113+   If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
114+ 
81-   The source code for this should be considered an example rather than  a tool.
115+   The source code for this should be considered an example rather than the
116+   ultimate tool.
82
83   .. versionchanged:: 2.3
84      :exc:`Error` is raised if any exceptions occur during copying, rather than
85      printing a message.
86
87   .. versionchanged:: 2.5
88      Create intermediate directories needed to create *dst*, rather than raising an
89      error. Copy permissions and times of directories using :func:`copystat`.
90
n126+   .. versionchanged:: 2.6
127+      Added the *ignore* argument to be able to influence what is being copied.
128+ 
91
92.. function:: rmtree(path[, ignore_errors[, onerror]])
93
94   .. index:: single: directory; deleting
95
n134+   Delete an entire directory tree; *path* must point to a directory (but not a
96-   Delete an entire directory tree. If *ignore_errors* is true, errors resulting
135+   symbolic link to a directory).  If *ignore_errors* is true, errors resulting
97   from failed removals will be ignored; if false or omitted, such errors are
n98-   handled by calling a handler specified by *onerror* or, if that is omitted, they
n137+   handled by calling a handler specified by *onerror* or, if that is omitted,
99-   raise an exception.
138+   they raise an exception.
100
n101-   If *onerror* is provided, it must be a callable that accepts three parameters:
n140+   If *onerror* is provided, it must be a callable that accepts three
102-   *function*, *path*, and *excinfo*. The first parameter, *function*, is the
141+   parameters: *function*, *path*, and *excinfo*. The first parameter,
103-   function which raised the exception; it will be :func:`os.listdir`,
142+   *function*, is the function which raised the exception; it will be
104-   :func:`os.remove` or :func:`os.rmdir`.  The second parameter, *path*, will be
143+   :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
144+   :func:`os.rmdir`.  The second parameter, *path*, will be the path name passed
105-   the path name passed to *function*.  The third parameter, *excinfo*, will be the
145+   to *function*.  The third parameter, *excinfo*, will be the exception
106-   exception information return by :func:`sys.exc_info`.  Exceptions raised by
146+   information return by :func:`sys.exc_info`.  Exceptions raised by *onerror*
107-   *onerror* will not be caught.
147+   will not be caught.
148+ 
149+   .. versionchanged:: 2.6
150+      Explicitly check for *path* being a symbolic link and raise :exc:`OSError`
151+      in that case.
108
109
110.. function:: move(src, dst)
111
112   Recursively move a file or directory to another location.
113
n114-   If the destination is on our current filesystem, then simply use rename.
n158+   If the destination is on the current filesystem, then simply use rename.
115-   Otherwise, copy src to the dst and then remove src.
159+   Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
116
117   .. versionadded:: 2.3
118
119
120.. exception:: Error
121
n122-   This exception collects exceptions that raised during a mult-file operation. For
n166+   This exception collects exceptions that raised during a multi-file operation. For
123   :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*,
124   *dstname*, *exception*).
125
126   .. versionadded:: 2.3
127
128
129.. _shutil-example:
130
131Example
132-------
133
134This example is the implementation of the :func:`copytree` function, described
135above, with the docstring omitted.  It demonstrates many of the other functions
136provided by this module. ::
137
n138-   def copytree(src, dst, symlinks=0):
n182+   def copytree(src, dst, symlinks=False, ignore=None):
139       names = os.listdir(src)
n184+       if ignore is not None:
185+           ignored_names = ignore(src, names)
186+       else:
187+           ignored_names = set()
188+ 
140-       os.mkdir(dst)
189+       os.makedirs(dst)
190+       errors = []
141       for name in names:
n192+           if name in ignored_names:
193+               continue
142           srcname = os.path.join(src, name)
143           dstname = os.path.join(dst, name)
144           try:
145               if symlinks and os.path.islink(srcname):
146                   linkto = os.readlink(srcname)
147                   os.symlink(linkto, dstname)
148               elif os.path.isdir(srcname):
n149-                   copytree(srcname, dstname, symlinks)
n201+                   copytree(srcname, dstname, symlinks, ignore)
150               else:
151                   copy2(srcname, dstname)
n204+               # XXX What about devices, sockets etc.?
152           except (IOError, os.error), why:
n153-               print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
n206+               errors.append((srcname, dstname, str(why)))
207+           # catch the Error from the recursive copytree so that we can
208+           # continue with other files
209+           except Error, err:
210+               errors.extend(err.args[0])
211+       try:
212+           copystat(src, dst)
213+       except WindowsError:
214+           # can't copy file access times on Windows
215+           pass
216+       except OSError, why:
217+           errors.extend((src, dst, str(why)))
218+       if errors:
219+           raise Error, errors
154
t221+Another example that uses the :func:`ignore_patterns` helper::
222+ 
223+   from shutil import copytree, ignore_patterns
224+ 
225+   copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
226+ 
227+This will copy everything except ``.pyc`` files and files or directories whose
228+name starts with ``tmp``.
229+ 
230+Another example that uses the *ignore* argument to add a logging call::
231+ 
232+   from shutil import copytree
233+   import logging
234+ 
235+   def _logpath(path, names):
236+       logging.info('Working in %s' % path)
237+       return []   # nothing will be ignored
238+ 
239+   copytree(source, destination, ignore=_logpath)
240+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op