【Python】使用Python壓縮檔/檔案夾

來源:互聯網
上載者:User

標籤:compress   dir   __name__   for   def   os.walk   開始   nis   post   

【Python壓縮檔夾】匯入“zipfile”模組

 1 def zip_ya(startdir,file_news): 2     startdir = ".\\123"  #要壓縮的檔案夾路徑 3     file_news = startdir +‘.zip‘ # 壓縮後檔案夾的名字 4     z = zipfile.ZipFile(file_news,‘w‘,zipfile.ZIP_DEFLATED) #參數一:檔案夾名 5     for dirpath, dirnames, filenames in os.walk(startdir): 6         fpath = dirpath.replace(startdir,‘‘) #這一句很重要,不replace的話,就從根目錄開始複製 7         fpath = fpath and fpath + os.sep or ‘‘#這句話理解我也點鬱悶,實現當前檔案夾以及包含的所有檔案的壓縮 8         for filename in filenames: 9             z.write(os.path.join(dirpath, filename),fpath+filename)10             print (‘壓縮成功‘)11     z.close()12 13 if__name__=="__main__"14     startdir = ".\\123"  #要壓縮的檔案夾路徑15     file_news = startdir +‘.zip‘ # 壓縮後檔案夾的名字 16     zip_ya(startdir,file_news)

【python壓縮檔】匯入“zipfile”模組

import zipfiledef zip_files( files, zip_name ):    zip = zipfile.ZipFile( zip_name, ‘w‘, zipfile.ZIP_DEFLATED )    for file in files:        print (‘compressing‘, file)        zip.write( file )    zip.close()    print (‘compressing finished‘)files = [‘.\\123.txt‘,‘.\\3.txt‘]#檔案的位置,多個檔案用“,”隔開zip_file = ‘.\\m66y.zip‘#壓縮包名字zip_files(files, zip_file)

 

【Python】使用Python壓縮檔/檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.