python zipfile模块的文件操作
发布时间:2024-07-30 09:46:50

1、用于读取zip文件
>>>importzipfile,os
>>>os.chdir('C:\\')#movetothefolderwithexample.zip
>>>exampleZip=zipfile.ZipFile('example.zip')
>>>exampleZip.namelist()
['spam.txt','cats/','cats/catnames.txt','cats/zophie.jpg']
>>>spamInfo=exampleZip.getinfo('spam.txt')
>>>spamInfo.file_size
13908
>>>spamInfo.compress_size
3828
>>>'Compressedfileis%sxsmaller!'%(round(spamInfo.file_size/spamInfo.compress_size,2))
'compresedfiles3.63xsmaler!'%(round(spamInfo.file_size/spamInfo.compress_size,2))
'compresedfiles3.63xsmaler!'
>>>exampleZip.close()2、zipfile.ZipFile()方法中的第二个参数zipfile.ZIP_deflated指定了deflate压缩算法,对各种类型的数据非常有效。
该代码将创建一个新的ZIP文件,称为new.zip,它包含spam.txt压缩内容。
就像写入文件一样,写入模式将删除ZIP文件中的所有原始内容。如果您只想将文件添加到原始ZIP文件中,请将a作为第二个参数传输到zipfile.ZipFile()以添加模式打开ZIP文件。
>>>importzipfile
>>>newZip=zipfile.ZipFile('new.zip','w')
>>>newZip.write('spam.txt',compress_type=zipfile.ZIP_DEFLATED)
>>>newZip.close()以上是python zipfile模块文件的操作方法,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
