import zipfile #zip_deflated 表明是壓縮的意思
#打開壓縮包
zf = zipfile.ZipFile("ceshi1005.zip","w",zipfile.ZIP_DEFLATED)
print(zf)
#寫入文件
#write("路徑","別名")
zf.write("/bin/cat","cat")
zf.write("/bin/ls","ls")
zf.write("/bin/chgrp","chgrp")
#關閉壓縮包
zf.close()linux
zf = zipfile.ZipFile("ceshi1005.zip","r")
#extractall("路徑") 解壓全部文件到一個文件夾當中
zf.extractall("./ceshi100005")算法
#zf.extract("文件名","路徑") 解壓單個文件到文件夾當中
zf.extract("ls","./ceshi100006")
zf.close()spa
#zipfile 一樣支持with語法
with zipfile.ZipFile("ceshi1005.zip","a",zipfile.ZIP_DEFLATED) as zf:
#在添加文件的時候,能夠動態爲該文件建立文件夾
zf.write("/bin/cp","/and/cp")
#(4)查看壓縮包中的內容
with zipfile.ZipFile("ceshi1005.zip","r") as zf:
res = zf.namelist()
print(res)orm
import tarfileip
tf = tarfile.open("ceshi001.tar","w",encoding="utf-8")
#add(路徑,別名) 添加文件到壓縮包當中
tf.add("/bin/dash","dash")
tf.add("/bin/dd","dd")
tf.add("/bin/df","/tmp/df")
#關閉壓縮包
tf.close() #327680
#按照gz 算法 建立一個.tar.gz 的壓縮包
tf = tarfile.open("ceshi001.tar.gz","w:gz",encoding="utf-8")
tf.add("/bin/dash","dash")
tf.add("/bin/dd","dd")
tf.add("/bin/df","/tmp/df")
tf.close() #162558
#按照bz2算法 建立一個.tar.bs2 的壓縮包
tf = tarfile.open("ceshi001.tar.bz2","w:bz2",encoding="utf-8")
tf.add("/bin/dash","dash")
tf.add("/bin/dd","dd")
tf.add("/bin/df","/tmp/df")
tf.close() #147524
#理論上:bz2算法壓縮包要比gz算法壓縮的包小utf-8
tf = tarfile.open("ceshi001.tar.gz","r",encoding="utf-8")
#一次性解壓全部
#tf.extractall("ceshi001")
#解壓單個文件
tf.extract("dd","ceshi001_dd")
tf.close()get
tarfile 有侷限性,不能對已經壓縮好的包進行追加文件
只能對光打包不壓縮的文件進行追加
#
#with tarfile.open("ceshi001.tar.bz2","a",encoding="utf-8") as tf:
with tarfile.open("ceshi001.tar","a",encoding="utf-8") as tf:
#add(路徑,別名)
tf.add("/bin/sleep","sleep")it
with tarfile.open("ceshi001.tar","r",encoding="utf-8") as tf:
res = tf.getnames()
print(res)
##對tarfile 的追加進行改寫
(1)把原來的壓縮包進行解壓
(2)把要追加的文件塞進去
(3)從新過濾,從新打包
import os
#__file__
res = os.getcwd()
path1 = os.path.join(res,"ceshi001.tar.bz2")
path2 = os.path.join(res,"ceshi0011")
print(path1) #/mnt/hgfs/pylinux/ceshi001.bar.bz2
print(path2) #/mnt/hgfs/pylinux/ceshi0011
#(1)把原來的壓縮包進行解壓
with tarfile.open(path1,mode="r",encoding="utf-8") as tf:
tf.extractall(path2) #把解壓出來的文件放在ceshi0011上
#(2) 把要追加的文件塞進去
#os.system("cp -a /bin/login " + path2)
os.system("cp -a /bin/login {}".format(path2))
#(3) 開始過濾,dd這個文件過濾不要了
lst = os.listdir(path2)
with tarfile.open(path1,"w:bz2",encoding="utf-8") as tf:
for i in lst:
path_new = os.path.join(path2,i)
if i != "dd":
#add(路徑,文件/文件夾)
tf.add(path_new,i)form