shutil模塊提供了大量的文件的高級操做。特別針對文件拷貝和刪除,主要功能爲目錄和文件操做以及壓縮操做。python
shutil 模塊方法:ssh
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.make_archive)code
# 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)