python模組之shutil模組

2021-08-21 09:20:53 字數 2725 閱讀 3064

高階的 檔案、資料夾、壓縮包 處理模組

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

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

import shutil

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

shutil.copyfile(src, dst)

拷貝檔案

shutil.copyfile('f1.log', 'f2.log') #目標檔案無需存在

shutil.copymode(src, dst)#僅拷貝許可權。內容、組、使用者均不變

shutil.copymode('f1.log', 'f2.log') #目標檔案必須存在

shutil.copystat(src, dst)#僅拷貝狀態的資訊,包括:mode bits, atime, mtime, flags

shutil.copystat('f1.log', 'f2.log') #目標檔案必須存在

shutil.copy(src, dst)#拷貝檔案和許可權

import shutil

shutil.copy('f1.log', 'f2.log')

shutil.copy2(src, dst)#拷貝檔案和狀態資訊

import shutil

shutil.copy2('f1.log', 'f2.log')

shutil.ignore_patterns(*patterns)

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

遞迴的去拷貝資料夾

import shutil

shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目標目錄不能存在,注意對folder2目錄父級目錄要有可寫許可權,ignore的意思是排除 

拷貝軟鏈結

import shutilshutil.copytree('f1', 'f2', symlinks=true, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))#通常的拷貝都把軟連線拷貝成硬鏈結,即對待軟連線來說,建立新的檔案

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

遞迴的去刪除檔案

1 import shutil

2  3 shutil.rmtree('folder1')

shutil.move(src, dst)

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

1 import shutil

2  3 shutil.move('folder1', 'folder3')

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

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

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

base_name: 壓縮包的檔名,也可以是壓縮包的路徑。只是檔名時,則儲存至當前目錄,否則儲存至指定路徑,

如 data_bak                       =>儲存至當前路徑

如:/tmp/data_bak =>儲存至/tmp/

format:

壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」

root_dir:

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

owner:

使用者,預設當前使用者

group:

組,預設當前組

logger:

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

1 #將 /data 下的檔案打包放置當前程式目錄

2 import shutil

3 ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')

4   

5   

6 #將 /data下的檔案打包放置 /tmp/目錄

7 import shutil

8 ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data') 

zip檔案壓縮解壓縮

import zipfile

# 壓縮

z = zipfile.zipfile('laxi.zip', 'w')

z.write('a.log')

z.write('data.data')

z.close()

# 解壓

z = zipfile.zipfile('laxi.zip', 'r')

z.extractall(path='.')

z.close()

tarfile壓縮解壓縮

import tarfile

壓縮t=tarfile.open('/tmp/egon.tar','w')

t.add('/test1/a.py',arcname='a.bak')

t.add('/test1/b.py',arcname='b.bak')

t.close()

解壓t=tarfile.open('/tmp/egon.tar','r')

t.extractall('/egon')

t.close()

python之shutil模組的使用

shutil模組 shutil模組是一種高階的檔案操作工具,其對檔案的複製與刪除操作非常強大,shutil 名字 於 shell utilities,該模組擁有許多檔案 夾 操作的功能,包括複製 移動 重新命名 刪除 壓縮,解壓等等 常用功能 shutil.copy 實現檔案複製功能,返回值是複製成...

Python常用模組 shutil模組

import shutil copy 功能 複製檔案 格式 shutil.copy 檔案 目標位址 返回值 複製之後的路徑 copy2 功能 複製檔案,保留元資料 格式 shutil.copy2 檔案 目標位址 返回值 複製之後的路徑 copyfileobj 將乙個檔案的內容拷貝的另外乙個檔案當中 ...

模組之shutil模組模組詳解

shutil模組是高階的 檔案 資料夾 壓縮包 處理模組 shutil.copyfileobj fsrc,fdst length 將檔案內容拷貝到另乙個檔案中 shutil.copyfile src,dst 拷貝檔案 shutil.copymode src,dst 僅拷貝許可權。內容 組 使用者均不...