/Doc/library/shutil.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 240 lines · 171 code · 69 blank · 0 comment · 0 complexity · dd147b946c6dd983e06fb3016dac7b4d MD5 · raw file

  1. :mod:`shutil` --- High-level file operations
  2. ============================================
  3. .. module:: shutil
  4. :synopsis: High-level file operations, including copying.
  5. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  6. .. partly based on the docstrings
  7. .. index::
  8. single: file; copying
  9. single: copying files
  10. The :mod:`shutil` module offers a number of high-level operations on files and
  11. collections of files. In particular, functions are provided which support file
  12. copying and removal. For operations on individual files, see also the
  13. :mod:`os` module.
  14. .. warning::
  15. Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
  16. can't copy all file metadata.
  17. On POSIX platforms, this means that file owner and group are lost as well
  18. as ACLs. On Mac OS, the resource fork and other metadata are not used.
  19. This means that resources will be lost and file type and creator codes will
  20. not be correct. On Windows, file owners, ACLs and alternate data streams
  21. are not copied.
  22. .. function:: copyfileobj(fsrc, fdst[, length])
  23. Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
  24. The integer *length*, if given, is the buffer size. In particular, a negative
  25. *length* value means to copy the data without looping over the source data in
  26. chunks; by default the data is read in chunks to avoid uncontrolled memory
  27. consumption. Note that if the current file position of the *fsrc* object is not
  28. 0, only the contents from the current file position to the end of the file will
  29. be copied.
  30. .. function:: copyfile(src, dst)
  31. Copy the contents (no metadata) of the file named *src* to a file named *dst*.
  32. *dst* must be the complete target file name; look at :func:`copy` for a copy that
  33. accepts a target directory path. If *src* and *dst* are the same files,
  34. :exc:`Error` is raised.
  35. The destination location must be writable; otherwise, an :exc:`IOError` exception
  36. will be raised. If *dst* already exists, it will be replaced. Special files
  37. such as character or block devices and pipes cannot be copied with this
  38. function. *src* and *dst* are path names given as strings.
  39. .. function:: copymode(src, dst)
  40. Copy the permission bits from *src* to *dst*. The file contents, owner, and
  41. group are unaffected. *src* and *dst* are path names given as strings.
  42. .. function:: copystat(src, dst)
  43. Copy the permission bits, last access time, last modification time, and flags
  44. from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
  45. and *dst* are path names given as strings.
  46. .. function:: copy(src, dst)
  47. Copy the file *src* to the file or directory *dst*. If *dst* is a directory, a
  48. file with the same basename as *src* is created (or overwritten) in the
  49. directory specified. Permission bits are copied. *src* and *dst* are path
  50. names given as strings.
  51. .. function:: copy2(src, dst)
  52. Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just
  53. :func:`copy` followed by :func:`copystat`. This is similar to the
  54. Unix command :program:`cp -p`.
  55. .. function:: ignore_patterns(\*patterns)
  56. This factory function creates a function that can be used as a callable for
  57. :func:`copytree`\'s *ignore* argument, ignoring files and directories that
  58. match one of the glob-style *patterns* provided. See the example below.
  59. .. versionadded:: 2.6
  60. .. function:: copytree(src, dst[, symlinks=False[, ignore=None]])
  61. Recursively copy an entire directory tree rooted at *src*. The destination
  62. directory, named by *dst*, must not already exist; it will be created as well
  63. as missing parent directories. Permissions and times of directories are
  64. copied with :func:`copystat`, individual files are copied using
  65. :func:`copy2`.
  66. If *symlinks* is true, symbolic links in the source tree are represented as
  67. symbolic links in the new tree; if false or omitted, the contents of the
  68. linked files are copied to the new tree.
  69. If *ignore* is given, it must be a callable that will receive as its
  70. arguments the directory being visited by :func:`copytree`, and a list of its
  71. contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
  72. called recursively, the *ignore* callable will be called once for each
  73. directory that is copied. The callable must return a sequence of directory
  74. and file names relative to the current directory (i.e. a subset of the items
  75. in its second argument); these names will then be ignored in the copy
  76. process. :func:`ignore_patterns` can be used to create such a callable that
  77. ignores names based on glob-style patterns.
  78. If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
  79. The source code for this should be considered an example rather than the
  80. ultimate tool.
  81. .. versionchanged:: 2.3
  82. :exc:`Error` is raised if any exceptions occur during copying, rather than
  83. printing a message.
  84. .. versionchanged:: 2.5
  85. Create intermediate directories needed to create *dst*, rather than raising an
  86. error. Copy permissions and times of directories using :func:`copystat`.
  87. .. versionchanged:: 2.6
  88. Added the *ignore* argument to be able to influence what is being copied.
  89. .. function:: rmtree(path[, ignore_errors[, onerror]])
  90. .. index:: single: directory; deleting
  91. Delete an entire directory tree; *path* must point to a directory (but not a
  92. symbolic link to a directory). If *ignore_errors* is true, errors resulting
  93. from failed removals will be ignored; if false or omitted, such errors are
  94. handled by calling a handler specified by *onerror* or, if that is omitted,
  95. they raise an exception.
  96. If *onerror* is provided, it must be a callable that accepts three
  97. parameters: *function*, *path*, and *excinfo*. The first parameter,
  98. *function*, is the function which raised the exception; it will be
  99. :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
  100. :func:`os.rmdir`. The second parameter, *path*, will be the path name passed
  101. to *function*. The third parameter, *excinfo*, will be the exception
  102. information return by :func:`sys.exc_info`. Exceptions raised by *onerror*
  103. will not be caught.
  104. .. versionchanged:: 2.6
  105. Explicitly check for *path* being a symbolic link and raise :exc:`OSError`
  106. in that case.
  107. .. function:: move(src, dst)
  108. Recursively move a file or directory to another location.
  109. If the destination is on the current filesystem, then simply use rename.
  110. Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
  111. .. versionadded:: 2.3
  112. .. exception:: Error
  113. This exception collects exceptions that raised during a multi-file operation. For
  114. :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*,
  115. *dstname*, *exception*).
  116. .. versionadded:: 2.3
  117. .. _shutil-example:
  118. Example
  119. -------
  120. This example is the implementation of the :func:`copytree` function, described
  121. above, with the docstring omitted. It demonstrates many of the other functions
  122. provided by this module. ::
  123. def copytree(src, dst, symlinks=False, ignore=None):
  124. names = os.listdir(src)
  125. if ignore is not None:
  126. ignored_names = ignore(src, names)
  127. else:
  128. ignored_names = set()
  129. os.makedirs(dst)
  130. errors = []
  131. for name in names:
  132. if name in ignored_names:
  133. continue
  134. srcname = os.path.join(src, name)
  135. dstname = os.path.join(dst, name)
  136. try:
  137. if symlinks and os.path.islink(srcname):
  138. linkto = os.readlink(srcname)
  139. os.symlink(linkto, dstname)
  140. elif os.path.isdir(srcname):
  141. copytree(srcname, dstname, symlinks, ignore)
  142. else:
  143. copy2(srcname, dstname)
  144. # XXX What about devices, sockets etc.?
  145. except (IOError, os.error), why:
  146. errors.append((srcname, dstname, str(why)))
  147. # catch the Error from the recursive copytree so that we can
  148. # continue with other files
  149. except Error, err:
  150. errors.extend(err.args[0])
  151. try:
  152. copystat(src, dst)
  153. except WindowsError:
  154. # can't copy file access times on Windows
  155. pass
  156. except OSError, why:
  157. errors.extend((src, dst, str(why)))
  158. if errors:
  159. raise Error, errors
  160. Another example that uses the :func:`ignore_patterns` helper::
  161. from shutil import copytree, ignore_patterns
  162. copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
  163. This will copy everything except ``.pyc`` files and files or directories whose
  164. name starts with ``tmp``.
  165. Another example that uses the *ignore* argument to add a logging call::
  166. from shutil import copytree
  167. import logging
  168. def _logpath(path, names):
  169. logging.info('Working in %s' % path)
  170. return [] # nothing will be ignored
  171. copytree(source, destination, ignore=_logpath)