python shutil模块简单介绍
简介

shutil模块提供了大量的文件的高级操作。特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作。

shutil 模块方法:

    copy(src, dst)
Copy data and mode bits ("cp src dst") # 复制数据和权限,相对于cp命令 The destination may be a directory. # 目标数据可以为目录 copy2(src, dst)
Copy data and all stat info ("cp -p src dst"). # 拷贝文件和状态信息 The destination may be a directory. copyfile(src, dst) # 拷贝文件
Copy data from src to dst copyfileobj(fsrc, fdst, length=16384) # 将文件内容拷贝到另一个文件
copy data from file-like object fsrc to file-like object fdst copymode(src, dst) # 仅拷贝权限,内容,用户,组不变
Copy mode bits from src to dst copystat(src, dst) # 仅拷贝状态信息
Copy all stat info (mode bits, atime, mtime, flags) from src to dst copytree(src, dst, symlinks=False, ignore=None) # 递归复制
Recursively copy a directory tree using copy2(). get_archive_formats() # 返回支持的 压缩格式列表
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) ignore_patterns(*patterns) # 相当于copytree
Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns
that are used to exclude files
# 模式是一个序列,用于排除文件glob方式模式 make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None)
Create an archive file (eg. zip or tar). # 创建压缩文件
参数介绍:
base_name: 压缩包的文件名, 也可以使压缩包的路径.
format: 压缩种类
root_dir: 要压缩的文件夹路径,默认为当前路径
owner: 压缩用户,默认为当前用户
group: 组,默认为当前组 move(src, dst) # 移动文件,相对于Linux的“mv”命令
Recursively move a file or directory to another location. This is
similar to the Unix "mv" command. register_archive_format(name, function, extra_args=None, description='')
Registers an archive format. # 返回支持的 压缩格式列表 rmtree(path, ignore_errors=False, onerror=None) # 递归删除目录树
Recursively delete a directory tree.
shutil 模块使用简单示例:

创建压缩文件(shutil.make_archive)

# cat shutil_test01.py
#!/usr/bin/env python
# -*- conding:utf-8 -*- from shutil import make_archive
import os archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
make_archive(archive_name, 'gztar', root_dir)
04-27 04:47