压缩模快- zipfile (后缀为zip)
import zipfile
格式: with zipfile.ZipFile("file",mode,zipfile.ZIP_DEFLATED)
功能: 创建一个zip文件,表示一个zip对象
参数:file 表示压缩包路径,或类对象文件
参数mode表示模式 ,默认为r 为w 就是新创建一个压缩包
zipfile.ZIP_STORED 只是存储模式,不会对文件进行压缩,这个是默认值
zipfile.ZIP_DEFLATED 对文件进行压缩 (一般都用这个)
-如果要操作的zip文件大小超过2G,应该将allowZip64设置为True。
zf = zipfile.ZipFile("1234.zip","w",zipfile.ZIP_DEFLATED)
zf.write("/day18/mv",'cp')
zf.close()
zf = zipfile.ZipFile("1234.zip","r",zipfile.ZIP_DEFLATED)
zf.extract("cp","bin")
zf.extractall("cp1","all")
zf.close()
with zipfile.ZipFile("1234.zip","a",zipfile.ZIP_DAFLATED)
zp.write("/day18/haha",'cp2')
with zipfile.ZipFile("1234.zip","r",zipfile.ZIP_DEFLATED)
ls = zf.namelist()
print(ls)
tarfile模块
后缀:
.tar 普通压缩大小不变
.tar.gz 压缩后文件变小
.tar.bz2 压缩后最小
import tarfile
(1)
tf = tarfile.open("zs.tar","w")
tf.add("w.txt","ww")
tf.close()
(2)
tf = tarfile.open("ceshi0729_1.tar","w",encoding="utf-8")
tf.add("/bin/echo","echo")
tf.add("/bin/ed","ed")
tf.add("/bin/fuser","/tmp/fuser")
tf.close()
.tar.gz压缩包
tf = tarfile.open("zs.tar.gz","w",encoding="utf-8")
tf.add("w.txt","ww")
tf.close()
.tar.bz2
tf = tarfile.open("zs.tar","w",encoding="utf-8")
tf.add("w.txt","ww")
tf.close()
解压
tf = tarfile.open("zs.tar","r",encoding="utf-8")
tf.extract("ww","aa")