1. 程式人生 > 程式設計 >Python shutil模組用法例項分析

Python shutil模組用法例項分析

本文例項講述了Python shutil模組用法。分享給大家供大家參考,具體如下:

shutil模組

主要作用與拷貝檔案用的。

1.shutil.copyfileobj(檔案1,檔案2):將檔案1的資料覆蓋copy給檔案2。

import shutil
f1 = open("1.txt",encoding="utf-8")
f2 = open("2.txt","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)

2.shutil.copyfile(檔案1,檔案2):不用開啟檔案,直接用檔名進行覆蓋copy。

import shutil
shutil.copyfile("1.txt","3.txt")

3.shutil.copymode(檔案1,檔案2):之拷貝許可權,內容組,使用者,均不變。

def copymode(src,dst):
  """copy mode bits from src to dst"""
  if hasattr(os,'chmod'):
    st = os.stat(stc)
    mode = stat.S_IMODE(st.st_mode)
    os.chmod(dst,mode)

4.shutil.copystat(檔案1,檔案):只拷貝了許可權。

def copystat(src,dst):
  """將所有的狀態資訊(模式位、時間、時間、標誌)從src複製到dst"""
  st = os.stat(src)
  mode = stat.S_IMODE(st.st_mode)
  if hasattr(os,'utime'):
    os.utime(dst,(st.st_atime,st.st_mtime))
  if hasattr(os,'chmod')
    os.chmod(dst,mode)
  if hasattr(os,'chflags') and hasattr(st,'st_flags'):
    try:
      os.chflags(dst,st.st_flags)
    except OSError,why:
      for err in 'EOPNOTSUPP','ENOTSUP':
        if hasattr(errno,err) and why.errno == getattr(errno,err):
          break
        else:
          raise

5.shutil.copy(檔案1,檔案2):拷貝檔案和許可權都進行copy。

def copy(src,dst):
  """copy data and mode bits ("cp src dst")
  The destination may be a directory.
  """
  if os.path.isdir(dst):
    dst = os.path.join(dst,os.path.basename(src))
    copyfile(src,dst)
    copymode(src,dst)

6.shutil.copy2(檔案1,檔案2):拷貝了檔案和狀態資訊。

7.shutil.copytree(源目錄,目標目錄):可以遞迴copy多個目錄到指定目錄下。

  • shutil.ignore_patterns(*patterns)
  • shutil.copytree(src,dst,symlinks=False,ignore=None)

遞迴的去拷貝檔案

例如:copytree(source,destination,ignore=ignore_patterns('*.pyc','tmp*'))

8.shutil.rmtree(目標目錄):可以遞迴刪除目錄下的目錄及檔案。

9.shutil.move(原始檔,指定路徑):遞迴移動一個檔案。

10.shutil.make_archive():可以壓縮,打包檔案。

import shutil
shutil.make_archive("shutil_archive_test","zip","D:\新建資料夾 (2)")

11.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",root_dir='/Users/wupeiqi/Downloads/test')

shutil 對壓縮包的處理是呼叫 ZipFile 和 TarFile 兩個模組來進行的,詳細:

zipfile 壓縮解壓

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

tarfile 壓縮解壓

import tarfile
# 壓縮
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip',arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip',arcname='cmdb.zip')
tar.close()
# 解壓
tar = tarfile.open('your.tar','r')
tar.extractall() # 可設定解壓地址
tar.close()

第二種方法:

import zipfile
z = zipfile.ZipFile("day5.zip","w")
z.write("a")

解壓:

z.extractall("a")

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python檔案與目錄操作技巧彙總》、《Python文字檔案操作技巧彙總》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》及《Python入門與進階經典教程》

希望本文所述對大家Python程式設計有所幫助。