Python 基础之压缩模块zipfile与tarfile

一.压缩模块 zipfile

(1)创建一个zip压缩包

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

(2)解压文件

zf = zipfile.ZipFile("ceshi1005.zip","r")
#extractall("路径") 解压所有文件到一个文件夹当中
zf.extractall("./ceshi100005")


#zf.extract("文件名","路径")  解压单个文件到文件夹当中
zf.extract("ls","./ceshi100006")
zf.close()

(3)追加文件

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

tarfile 压缩包

import tarfile

(1)创建tarfile压缩包

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算法压缩的包小

(2) 解压文件

tf = tarfile.open("ceshi001.tar.gz","r",encoding="utf-8")
#一次性解压所有
#tf.extractall("ceshi001")
#解压单个文件
tf.extract("dd","ceshi001_dd")
tf.close()

(3)追加文件

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

(4)查看压缩包的内容

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)

posted @ 2019-03-19 19:59  pycoder_hsz  阅读(299)  评论(0编辑  收藏  举报