新聞中心
這里有您想知道的互聯網營銷解決方案
創(chuàng)新互聯Python教程:pythonzipfile模塊的文件操作
1、用于讀取zip文件

>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.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
>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo.compress_size, 2))
'Compressed file is 3.63x smaller!'
>>> exampleZip.close()
2、zipfile.ZipFile()方法中的第二個參數zipfile.ZIP_DEFLATED指定了deflate壓縮算法,對各種類型的數據非常有效。
這個代碼將創(chuàng)建一個新的ZIP文件,叫做new.zip,它包含了spam.txt壓縮的內容。
就像寫入文件一樣,寫入模式也會刪除ZIP文件中的所有原始內容。若僅想將文件添加到原來的ZIP文件中,請將a作為第二個參數傳輸到zipfile.ZipFile(),以添加模式打開ZIP文件。
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()
以上就是python zipfile模塊文件操作的方法,希望對大家有所幫助。更多Python學習指路:創(chuàng)新互聯Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
文章名稱:創(chuàng)新互聯Python教程:pythonzipfile模塊的文件操作
網頁URL:http://m.fisionsoft.com.cn/article/cdpdcih.html


咨詢
建站咨詢
