Python中使用tarfile壓縮、解壓tar歸檔文件示例
Python自帶的tarfile模塊可以方便讀取tar歸檔文件,牛b的是可以處理使用gzip和bz2壓縮歸檔文件tar.gz和tar.bz2。
與tarfile對(duì)應(yīng)的是zipfile模塊,zipfile是處理zip壓縮的。請(qǐng)注意:os.system(cmd)可以使Python腳本執(zhí)行命令,當(dāng)然包括:tar -czf *.tar.gz *,tar -xzf *.tar.gz,unzip等,當(dāng)我覺得這樣盡管可以解決問題,但我覺得很業(yè)余。
使用tarfile壓縮
import tarfile
#創(chuàng)建壓縮包名
tar = tarfile.open("/tmp/tartest.tar.gz","w:gz")
#創(chuàng)建壓縮包
for root,dir,files in os.walk("/tmp/tartest"):
for file in files:
fullpath = os.path.join(root,file)
tar.add(fullpath)
tar.close()
使用tarfile解壓
def extract(tar_path, target_path):
try:
tar = tarfile.open(tar_path, "r:gz")
file_names = tar.getnames()
for file_name in file_names:
tar.extract(file_name, target_path)
tar.close()
except Exception, e:
raise Exception, e
其中open的原型是:
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)
mode的值有:
'r' or 'r:*' Open for reading with transparent compression (recommended).
'r:' Open for reading exclusively without compression.
'r:gz' Open for reading with gzip compression.
'r:bz2' Open for reading with bzip2 compression.
'a' or 'a:' Open for appending with no compression. The file is created if it does not exist.
'w' or 'w:' Open for uncompressed writing.
'w:gz' Open for gzip compressed writing.
'w:bz2' Open for bzip2 compressed writing.
更多請(qǐng)參考:tarfile — Read and write tar archive files
- 淺析Python中壓縮zipfile與解壓縮tarfile模塊的使用
- python tarfile壓縮包操作保姆級(jí)教程
- python標(biāo)準(zhǔn)庫(kù)壓縮包模塊zipfile和tarfile詳解(常用標(biāo)準(zhǔn)庫(kù))
- Python標(biāo)準(zhǔn)庫(kù)之zipfile和tarfile模塊的使用
- Python實(shí)現(xiàn)批量壓縮解壓文件(zip、rar)
- python 實(shí)現(xiàn)tar文件壓縮解壓的實(shí)例詳解
- Python壓縮解壓縮zip文件及破解zip文件密碼的方法
- Python使用tarfile模塊實(shí)現(xiàn)免費(fèi)壓縮解壓
相關(guān)文章
python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn)
這篇文章主要介紹了python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
在Mac OS上部署Nginx和FastCGI以及Flask框架的教程
這篇文章主要介紹了在Mac OS上部署Nginx和FastCGI以及Flask框架的教程,Flask是Python下一個(gè)極簡(jiǎn)的web開放框架,需要的朋友可以參考下2015-05-05
python目標(biāo)檢測(cè)SSD算法訓(xùn)練部分源碼詳解
這篇文章主要為大家介紹了python目標(biāo)檢測(cè)SSD算法訓(xùn)練部分源碼詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python文字截圖識(shí)別OCR工具實(shí)例解析
這篇文章主要介紹了Python文字截圖識(shí)別OCR工具實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03

