天天看點

Python3之shutil子產品

一. 簡介

  shutil 是進階的檔案,檔案夾,壓縮包處理子產品。

二. 使用

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)

拷貝檔案和權限

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

shutil.copy2(src, dst)

拷貝檔案和狀态資訊

shutil.copy2('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

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

    如:www                        =>儲存至目前路徑

    如:/Users/wupeiqi/www =>儲存至/Users/wupeiqi/

  • format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要壓縮的檔案夾路徑(預設目前目錄)
  • owner: 使用者,預設目前使用者
  • group: 組,預設目前組
  • logger: 用于記錄日志,通常是logging.Logger對象
#将 /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 對壓縮包的處理是通過調用ZipFile 和 TarFile兩個子產品來進行的。

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()
      
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()