压缩模块 zipfile
# ### 压缩模块 zipfile # (1) 创建一个zip压缩包 import zipfile # zip_deflated 代表是压缩的意思 # 打开压缩包 zf = zipfile.ZipFile("ceshi1136.zip","w",zipfile.ZIP_DEFLATED) print(zf) # 写入文件 # write("路径","别名") zf.write("/bin/cat","qqq") zf.write("/bin/cp","chacl") zf.write("/bin/chgrp","chgrp") # 关闭压缩包 zf.close() # (2) 解压文件 zf = zipfile.ZipFile("ceshi1136.zip","r") # extractall("路径") 解压所有文件到一个文件夹当中 # zf.extractall("./ceshi1136") # zf.extract("文件名","路径") 解压单个文件到一个文件夹当中 zf.extract("chgrp","./ceshi1136_2") zf.close() # (3) 追加文件 # zipfile 同样支持with语法 with zipfile.ZipFile("ceshi1136.zip","a",zipfile.ZIP_DEFLATED) as zf: # 在添加文件的时候,可以动态为该文件创建文件夹 zf.write("/bin/cp","/abd/cp") # (4) 查看压缩包中的内容 with zipfile.ZipFile("ceshi1136.zip","r") as zf: res = zf.namelist() print(res)