python標準庫之shutil

2022-09-04 02:45:10 字數 2164 閱讀 3661

shutil模組是乙個高階的檔案處理模組

1.將檔案內容拷貝到另乙個檔案中

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

(copyfileobj方法只會拷貝檔案內容)

例子:shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

2.拷貝檔案

shutil.copyfile(src, dst)

(copyfile只拷貝檔案內容)

例子:shutil.copyfile('f1.log', 'f2.log')

3.拷貝檔案和許可權

shutil.copy(src, dst)

例子:shutil.copy('f1.log', 'f2.log')

4.拷貝檔案和狀態資訊

shutil.copy2(src, dst)

例子:shutil.copy2('f1.log', 'f2.log')

5.僅拷貝許可權. 內容、組、使用者均不變(前提是dst檔案存在,不然報錯)

shutil.copymode(src, dst)

例子:shutil.copymode('f1.log', 'f2.log')

6.僅拷貝狀態的資訊,即檔案屬性,包括:mode bits, atime, mtime, flags

shutil.copystat(src, dst)

例子:shutil.copystat('f1.log', 'f2.log')

7.忽略哪個檔案,有選擇性的拷貝

shutil.ignore_patterns(*patterns)

例子:shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

8.遞迴的去拷貝資料夾

shutil.copytree(src, dst, symlinks=false, ignore=none)

例子:shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

shutil.copytree('f1', 'f2', symlinks=true, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

9.遞迴的去刪除檔案

shutil.rmtree(path[, ignore_errors[, onerror]])

例子:shutil.rmtree('folder1')

10.遞迴的去移動檔案,它類似mv命令,其實就是重新命名

shutil.move(src, dst)

例子:shutil.move('folder1', 'folder3')

11.建立壓縮包並返回檔案路徑,例如:zip tar

shutil.make_archive(base_name, format,...)

base_name:壓縮包的檔名,也可以是壓縮包的路徑

format:壓縮包種類("zip", "tar", "bztar","gztar")

root_dir:要壓縮的資料夾路徑(預設當前目錄)

owner:使用者,預設當前使用者

group:組,預設當前組

logger:用於記錄日誌,通常是logging.logger物件

12.解壓檔案

shutil.unpack_archive('歸檔檔案路徑','解包目標資料夾')

13.獲取當前系統已註冊的歸檔檔案格式(字尾)

shutil.get_archive_formats()

14.功能:獲取當前系統已經註冊的解包檔案格式(字尾)

shutil.get_unpack_formats()

python3之sys模組以及shutil模組

本章節介紹sys模組以及shutil模組,分享給剛學python的小夥伴,一起學習,共同進步 sys模組import sys 獲取python的版本資訊 print sys.version print sys.ar 退出 sys.exit 1 shutil模組 import shutil 主要做複製...

Python標準庫之time, datetime包

python具有良好的時間和日期管理功能。實際上,計算機只會維護乙個掛鐘時間 wall clock time 這個時間是從某個固定時間起點到現在的時間間隔。時間起點的選擇與計算機相關,但一台計算機的話,這一時間起點是固定的。其它的日期資訊都是從這一時間計算得到的。此外,計算機還可以測量cpu實際上執...

Python標準庫之asyncio

asyncio是python 3.4版本引入的標準庫,直接內建了對非同步io的支援。asyncio的程式設計模型就是乙個訊息迴圈。我們從asyncio模組中直接獲取乙個eventloop的引用,然後把需要執行的協程扔到eventloop中執行,就實現了非同步io。用asyncio實現hello wo...