找压缩解压的代码,结果错误的太多,记录一下
压缩单个文件zip_file.write()是用来压缩单个文件的
ZipFile.write(filename, arcname, compress_type)
import zipfile,os fileName = r"E:\WORK\js.html" zipName = r"E:\WORK\js.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()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)