python zipfile使用

來源:互聯網
上載者:User

標籤:迴文   class   filename   pass   注釋   lis   read   rac   print   

the Python challenge中第6關使用到zipfile模組,於是記錄下zipfile的使用

zip日常使用只要是壓縮跟解壓操作,於是從這裡入手

1、壓縮

f=zipfile.ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=False)

建立一個zip檔案對象,壓縮是需要把mode改為‘w’,這個是源碼中的注釋Open the ZIP file with mode read "r", write "w" or append "a",a為追加壓縮,不會清空原來的zip

f.write(filename)

將檔案寫入zip檔案中,即將檔案壓縮

f.close()

將zip檔案對象關閉,與open一樣可以使用上下文with as

import zipfilewith zipfile.ZipFile(‘test.zip‘, mode=‘w‘) as zipf:   zipf.write(‘channel.zip‘)   zipf.write(‘zip_test.py‘)zipf = zipfile.ZipFile(‘test.zip‘)print zipf.namelist()

 

2、解壓

f.extract(directory)和f.exractall(directory)

import zipfilezipf = zipfile.ZipFile(‘test.zip‘)zipf.extractall(‘channel1‘)#將所有檔案解壓到channel1目錄下

 

進階應用程式 
1 zipfile.is_zipfile(filename) 
判斷一個檔案是不是壓縮檔 
2 ZipFile.namelist() 
返迴文件列表 
3 ZipFile.open(name[, mode[, password]]) 
開啟壓縮文檔中的某個檔案

 

if zipfile.is_zipfile(‘test.zip‘): #is_zipfile() 判斷是否似zip檔案   f = zipfile.ZipFile(‘test.zip‘)   files = f.namelist() #namelist() 返回zip壓縮包中的所有檔案   print ‘files:‘, files   mess = f.open(‘channel/readme.txt‘) #開啟zip壓縮包中的某個檔案,可讀可寫   print ‘mess:‘, mess.read()   f.close()

 

python zipfile使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.