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)