1. 程式人生 > ># Python3 shutil(高階檔案操作 模組)

# Python3 shutil(高階檔案操作 模組)

Python3 shutil(高階檔案操作 模組)

本文由 Luzhuo 編寫,轉發請保留該資訊.
原文: http://blog.csdn.net/Rozol/article/details/72672698

以下程式碼以Python3.6.1為例
Less is more!
高階檔案操作(拷貝 / 移動 / 壓縮 / 解壓縮)

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/21'
# shutil_demo.py 高階檔案操作(拷貝 / 移動 / 壓縮 / 解壓縮)

import
shutil def shutil_demo(): # 拷貝檔案 shutil.copy2('file.txt', 'temp.txt') # 拷貝目錄 shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True) # 刪除目錄 shutil.rmtree("temp", ignore_errors=True
) # 移動檔案/目錄 shutil.move("root", "temp", copy_function=shutil.copy2) # 獲取磁碟使用空間 total, used, free = shutil.disk_usage(".") print("當前磁碟共: %iGB, 已使用: %iGB, 剩餘: %iGB"%(total / 1073741824, used / 1073741824, free / 1073741824)) # 壓縮檔案 shutil.make_archive('Box', 'zip', 'temp') # 解壓檔案
shutil.unpack_archive('Box.zip') def shutil_func(): # 檔案和目錄操作 # shutil.copyfileobj(fsrc, fdst[, length]) // 拷貝檔案內容, 將fsrc檔案裡的內容copy到fdst檔案中, length:緩衝區大小 shutil.copyfileobj(open('file.txt', 'r'), open('temp.txt', 'w')) # shutil.copyfile(src, dst, *, follow_symlinks=True) // 拷貝檔案內容, 同copyfileobj, 如果dst=src,拋SameFileError異常, dst存在則替換 dst = shutil.copyfile('file.txt', 'temp.txt') # shutil.copymode(src, dst, *, follow_symlinks=True) // 僅拷貝許可權, 其他資訊不受影響 shutil.copymode('file.txt', 'temp.txt') # shutil.copystat(src, dst, *, follow_symlinks=True) // 拷貝狀態(許可權 / 最後訪問時間 / 上次修改時間 / 標誌), 其他不受迎影響 shutil.copystat('file.txt', 'temp.txt') # shutil.copy(src, dst, *, follow_symlinks=True) // 拷貝檔案(資料 / 許可權) dst = shutil.copy('file.txt', 'temp.txt') # shutil.copy2(src, dst, *, follow_symlinks=True) // 拷貝檔案(嘗試保留所有元資料) (不能拷貝建立時間,該時間可通過修改系統時間再建立檔案來實現) dst = shutil.copy2('file.txt', 'temp.txt') # shutil.ignore_patterns(*patterns) # symlinks:True(複製連結) / False(複製檔案), ignore=ignore_patterns("") // 忽略的檔案, copy_function=自定義複製函式, ignore_dangling_symlinks:True(忽略檔案不存在異常) / False(錯誤列表中新增異常) # shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) // 遞迴的複製根目錄下的整個目錄樹 dst = shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True) # shutil.rmtree(path, ignore_errors=False, onerror=None) // 刪除整個目錄樹, ignore_errors:是否忽略刪除失敗錯誤, onerror=def error(func, path, excinfo) shutil.rmtree("temp", ignore_errors=True) # shutil.move(src, dst, copy_function=copy2) // 遞迴移動檔案/目錄, 目錄存在則移動目錄, 檔案存在則覆蓋 dst = shutil.move("root", "temp", copy_function=shutil.copy2) total, used, free = shutil.disk_usage(".") # 給定路徑的磁碟使用情況統計資訊 # shutil.chown(path, user=None, group=None) // 修改使用者和組 (Unix可用) # shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) // 可執行檔案路徑, path:要查詢的路徑,未指定使用os.environ的結果 path_str = shutil.which("python") # 異常 try: pass except shutil.SameFileError: pass # copyfile()時,源和目錄是同一個檔案時,拋此異常 except shutil.Error: pass # copytree()時, 多檔案操作時引發的異常, 異常包含(srcname, dstname, excinfo) # 壓縮檔案操作 (封裝了zipfile / tarfile) # 建立歸檔檔案 base_name:壓縮包檔名, format:格式 zip / tar / bztar / xztar / gztar, root_dir:被歸檔的根目錄(預設當前目錄) # base_dir:儲存歸檔檔案的目錄(預設當前目錄) verbose:已棄用 dry_run:True(不建立歸檔,但記錄日誌), owner:使用者, group:使用者組, logger:日誌 # shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]) dst = shutil.make_archive('Box', 'zip', 'temp') # 注意:root_dir / base_dir至少寫一個,不然會造成壓縮包再次被打包的情況 # 分拆歸檔, filename:檔名, extract_dir:解壓到目錄(預設當前目錄), format:格式 (未提供,根據副檔名查詢,未找到引發ValueError) # shutil.unpack_archive(filename[, extract_dir[, format]]) shutil.unpack_archive('Box.zip') lists = shutil.get_archive_formats() # 返回支援的歸檔格式列表[(format, info)] lists = shutil.get_unpack_formats() # 返回所有註冊格式的列表[(name, extensions, description)] # 註冊壓縮格式, name:格式名, function:def func(base_name, base_dir, owner, group, dry_run, logger), extra_args:額外引數, description:說明資訊 # shutil.register_archive_format(name, function[, extra_args[, description]]) # shutil.unregister_archive_format(name) // 登出壓縮格式 # 註冊解壓格式 name:格式名, extensions:副檔名列表, function:實現函式 def unpack(filename, extract_dir), extra_args:額外引數(name, value), description:說明 # shutil.register_unpack_format(name, extensions, function[, extra_args[, description]]) # shutil.unregister_unpack_format(name) // 登出解壓格式 # 終端 # shutil.get_terminal_size(fallback=(columns, lines)) columns, lines = shutil.get_terminal_size() # 查詢終端大小(寬, 高), 無法查詢返回預設大小(80, 24) if __name__ == "__main__": shutil_demo() # shutil_func()