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)) 'Compressedfileis3.63xsmaller!' >>>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基础教程