shutil — 高级文件操作

源代码: Lib/shutil.py


The shutil 模块为文件和文件集合提供了许多高级操作。 尤其,提供了支持文件拷贝和移除的函数。对于单个文件的操作,另请参阅 os 模块。

警告

更高级文件拷贝函数 ( shutil.copy() , shutil.copy2() ) 无法拷贝所有文件元数据。

在 POSIX (便携式操作系统接口) 平台,这意味着文件所有者、组及 ACL 会丢失。在 Mac OS,将不使用资源分叉和其它元数据。这意味着资源会丢失,且文件类型和创建者代码将不正确。在 Windows,将不拷贝文件所有者、ACL 和替代数据流。

目录和文件操作

shutil. copyfileobj ( fsrc , fdst [ , length ] )

Copy the contents of the 像文件对象 fsrc to the file-like object fdst . The integer length , if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.

shutil. copyfile ( src , dst , * , follow_symlinks = True )

Copy the contents (no metadata) of the file named src to a file named dst 并返回 dst in the most efficient way possible. src and dst are 像路径对象 or path names given as strings.

dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError 被引发。

The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function.

follow_symlinks 为 False 且 src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.

引发 审计事件 shutil.copyfile 采用自变量 src , dst .

3.3 版改变: IOError 用于被引发而不是 OSError 。添加 follow_symlinks 自变量。现有返回 dst .

3.4 版改变: 引发 SameFileError 而不是 Error . Since the former is a subclass of the latter, this change is backward compatible.

3.8 版改变: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See 从属平台的高效拷贝操作 章节。