栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python import zipfile 压缩、解压文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python import zipfile 压缩、解压文件

找压缩解压的代码,结果错误的太多,记录一下

压缩单个文件

zip_file.write()是用来压缩单个文件的
ZipFile.write(filename, arcname, compress_type)

import zipfile,os

fileName = r"E:\WORK\js\2.html"
zipName = r"E:\WORK\js\2.zip"

zf = zipfile.ZipFile(zipName, 'w')
zf.write(fileName,'3.html')#fileName-文件名,3.html-压缩后的文件名称
zf.close()

(代码来源https://www.cnblogs.com/kk073000/archive/2013/04/11/2982539.html)

压缩整个文件夹下文件
import zipfile,os

zip = zipfile.ZipFile('……/PointAugment.zip', "w", zipfile.ZIP_DEFLATED)
#第一个参数是新建的压缩文件放置的位置,第三个是压缩方法
for path, dirnames, filenames in os.walk('……/PointAugment'):
 #walk函数里填需要压缩的文件夹路径
    fpath = path.replace('……/PointAugment', '')

    for filename in filenames:
        zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
解压文件夹
import zipfile
zFile = zipfile.ZipFile("MyMethod.zip", "r")
 
for fileM in zFile.namelist():
    zFile.extract(fileM, "MyMethod")
zFile.close();

乌龙:
报错AttributeError: ‘module‘ object has no attribute ‘ZipFile‘
因为我把自己建的脚本命名zipfile.py了……

看到过的错误代码:

import zipfile

zip_file = zipfile.ZipFile('new.zip','w')
# 把zfile整个目录下所有内容,压缩为new.zip文件
zip_file.write('zfile',compress_type=zipfile.ZIP_DEFLATED)
# 把c.txt文件压缩成一个压缩文件
# zip_file.write('c.txt',compress_type=zipfile.ZIP_DEFLATED)
zip_file.close()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/530268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号