Python 基礎 - 4.6 shutil 模組

來源:互聯網
上載者:User

標籤:記錄   error   mv命令   檔案夾路徑   返回   div   port   基礎   命令   

shutil 模組

進階的 檔案、檔案夾、壓縮包 處理模組

shutil.copyfileobj(fsrc, fdst[, length])
將檔案內容拷貝到另一個檔案中

import shutilshutil.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 shutilshutil.copy(‘f1.log‘, ‘f2.log‘)

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

import shutilshutil.copy2(‘f1.log‘, ‘f2.log‘)

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
遞迴的去拷貝檔案夾

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

shutil.rmtree(path[, ignore_errors[, onerror]])
遞迴的去刪除檔案

import shutilshutil.rmtree(‘folder1‘)

shutil.move(src, dst)
遞迴的去移動檔案,它類似mv命令,其實就是重新命名。

import shutilshutil.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對象
#將 /data 下的檔案打包放置當前程式目錄import shutilret = shutil.make_archive("data_bak", ‘gztar‘, root_dir=‘/data‘)#將 /data下的檔案打包放置 /tmp/目錄import shutilret = shutil.make_archive("/tmp/data_bak", ‘gztar‘, root_dir=‘/data‘)

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(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 基礎 - 4.6 shutil 模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.