標籤:迴文 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使用