天天看點

shutil子產品python的shutil子產品

python的shutil子產品

shutil:進階的 檔案、檔案夾、壓縮包 處理子產品

shutil.copyfileobj(fsrc, fdst[, length])(copyfileobj方法隻會拷貝檔案内容)

将檔案内容拷貝到另一個檔案中

import shutil

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

shutil.copyfile(src, dst)  (copyfile隻拷貝檔案内容)

拷貝檔案

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

shutil.copy(src, dst) 拷貝檔案和權限

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

shutil.copy2(src, dst)

拷貝檔案和狀态資訊

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

shutil.copymode(src, dst)  (前提是dst檔案存在,不然報錯)

僅拷貝權限。内容、組、使用者均不變

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

shutil.copystat(src, dst)

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

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

shutil.ignore_patterns(*patterns)  (忽略哪個檔案,有選擇性的拷貝)

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*'))      

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

遞歸的去删除檔案

shutil.rmtree('folder1')      

shutil.move(src, dst)

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

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

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

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

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

  • base_name: 壓縮包的檔案名,也可以是壓縮包的路徑。隻是檔案名時,則儲存至目前目錄,否則儲存至指定路徑, 如:www                        =>儲存至目前路徑 如:/Users/wupeiqi/www =>儲存至/Users/wupeiqi/
  • format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要壓縮的檔案夾路徑(預設目前目錄)
  • owner: 使用者,預設目前使用者
  • group: 組,預設目前組
  • logger: 用于記錄日志,通常是logging.Logger對象
    shutil子產品python的shutil子產品
    #将 /Users/wupeiqi/Downloads/test 下的檔案打包放置目前程式目錄
    
    import shutil
    
    ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
    
     
    #将 /Users/wupeiqi/Downloads/test 下的檔案打包放置 /Users/wupeiqi/目錄
    
    import shutil
    
    ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')      
    shutil子產品python的shutil子產品

shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個子產品來進行的,詳細:

shutil子產品python的shutil子產品
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()
z.close()      
shutil子產品python的shutil子產品
shutil子產品python的shutil子產品
import tarfile

# 壓縮
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
tar.close()

# 解壓
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可設定解壓位址
tar.close()      
shutil子產品python的shutil子產品

備注:zipfile壓縮不會保留檔案的狀态資訊,而tarfile會保留檔案的狀态資訊

繼續閱讀