Python實(shí)現(xiàn)壓縮文件夾與解壓縮zip文件的方法
本文實(shí)例講述了Python實(shí)現(xiàn)壓縮文件夾與解壓縮zip文件的方法。分享給大家供大家參考,具體如下:
直接上代碼
#coding=utf-8
#甄碼農(nóng)python代碼
#使用zipfile做目錄壓縮,解壓縮功能
import os,os.path
import zipfile
def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
#print arcname
zf.write(tar,arcname)
zf.close()
def unzip_file(zipfilename, unziptodir):
if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
zfobj = zipfile.ZipFile(zipfilename)
for name in zfobj.namelist():
name = name.replace('\\','/')
if name.endswith('/'):
os.mkdir(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir= os.path.dirname(ext_filename)
if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
outfile.close()
if __name__ == '__main__':
zip_dir(r'E:/python/learning',r'E:/python/learning/zip.zip')
unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')
運(yùn)行后在E:/python/learning目錄下生成zip.zip壓縮文件,同時(shí)在E:/python目錄下解壓縮zip.zip文件到learning2目錄。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲示例
這篇文章主要介紹了Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲,涉及Python隨機(jī)數(shù)運(yùn)算與數(shù)值判斷相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
Python 實(shí)現(xiàn)一個(gè)顏色色值轉(zhuǎn)換的小工具
這篇文章主要介紹了Python 實(shí)現(xiàn)一個(gè)顏色色值轉(zhuǎn)換的小工具的相關(guān)資料,需要的朋友可以參考下2016-12-12
Keras中的多分類損失函數(shù)用法categorical_crossentropy
這篇文章主要介紹了Keras中的多分類損失函數(shù)用法categorical_crossentropy,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python with語句上下文管理器兩種實(shí)現(xiàn)方法分析
這篇文章主要介紹了Python with語句上下文管理器兩種實(shí)現(xiàn)方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Python上下文管理器的相關(guān)概念、功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-02-02
python+opencv像素的加減和加權(quán)操作的實(shí)現(xiàn)
這篇文章主要介紹了python+opencv像素的加減和加權(quán)操作的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
一維信號小波去噪原理解析及python實(shí)現(xiàn)方式
這篇文章主要介紹了一維信號小波去噪原理解析及python實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Python數(shù)據(jù)分析Numpy中常用相關(guān)性函數(shù)
這篇文章主要為大家介紹了Python數(shù)據(jù)分析Numpy中常用相關(guān)性函數(shù)講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
親手教你用Python打造一款摸魚倒計(jì)時(shí)界面
前段時(shí)間在微博看到一段摸魚人的倒計(jì)時(shí)模板,感覺很有意思,于是我用了一個(gè)小時(shí)的時(shí)間寫一個(gè)頁面出來,下面小編把實(shí)現(xiàn)過程分享給大家,對Python摸魚倒計(jì)時(shí)界面感興趣的朋友一起看看吧2021-12-12

