Python實現壓縮資料夾與解壓縮zip檔案的方法

2022-09-27 03:03:20 字數 1473 閱讀 9021

直接上**

#coding=utf-8

#甄碼農python**

#使用zipfile做目錄壓縮,解壓縮功能

import os,os.path

import zipfile

def zip_dir(dirname,zipfilename):

www.cppcns.comfilelist =

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'qolce)

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')

執行後在e:/python/learning目錄下生成zip.zip壓縮檔案,同時在e:/python目錄下解壓縮zip.zip檔案到learning2目錄。

python壓縮資料夾

usr bin python encoding utf 8 import time import os zip a whole directory and its sub directories and files os.walk 可以得到乙個三元tupple dirpath,dirnames,fi...

python 壓縮資料夾

def zip ya start dir start dir start dir 要壓縮的資料夾路徑 file news start dir zip 壓縮後資料夾的名字 z zipfile.zipfile file news,w zipfile.zip deflated for dir path,d...

python壓縮資料夾

壓縮 import os import tarfile 壓縮path1 d pycode tar num1 deftext path path list os.listdir path 以列表的形式,檢索資料夾下的檔案 for i in path list 迴圈遍歷列表 full path os.p...