Python中使用tarfile壓縮、解壓tar歸檔文件示例
Python自帶的tarfile模塊可以方便讀取tar歸檔文件,牛b的是可以處理使用gzip和bz2壓縮歸檔文件tar.gz和tar.bz2。
與tarfile對應(yīng)的是zipfile模塊,zipfile是處理zip壓縮的。請注意: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.
更多請參考:tarfile — Read and write tar archive files
- 淺析Python中壓縮zipfile與解壓縮tarfile模塊的使用
- python tarfile壓縮包操作保姆級教程
- python標(biāo)準(zhǔn)庫壓縮包模塊zipfile和tarfile詳解(常用標(biāo)準(zhǔn)庫)
- Python標(biāo)準(zhǔn)庫之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統(tǒng)計(jì)文章中單詞出現(xiàn)次數(shù)實(shí)例
在本篇文章里小編給大家整理的是關(guān)于python統(tǒng)計(jì)文章中單詞出現(xiàn)次數(shù)實(shí)例,需要的朋友們參考學(xué)習(xí)下。2020-02-02Python+Opencv實(shí)現(xiàn)把圖片、視頻互轉(zhuǎn)的示例
這篇文章主要介紹了Python+Opencv實(shí)現(xiàn)把圖片、視頻互轉(zhuǎn)的示例,幫助大家更好的理解和實(shí)用python,感興趣的朋友可以了解下2020-12-12Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu)詳解【數(shù)字、字符串、列表、元組、集合、字典】
這篇文章主要介紹了Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu),結(jié)合實(shí)例形式分析了Python數(shù)字、字符串、列表、元組、集合、字典等基本數(shù)據(jù)類型功能、原理及相關(guān)使用技巧,需要的朋友可以參考下2019-06-06使用Python在Windows下獲取USB PID&VID的方法
今天小編就為大家分享一篇使用Python在Windows下獲取USB PID&VID的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07