python壓縮資料夾

2021-07-24 07:19:05 字數 1325 閱讀 8036

#! /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, filenames),其中第乙個為起始路徑,

第二個為起始路徑下的資料夾,第三個是起始路徑下的檔案。'''

import os,zipfile

from os.path import join

def zipfolder(foldername,filename):

print foldername

empty_dirs=

zip = zipfile.zipfile(filename,'w',zipfile.zip_deflated)

for root,dirs,files in os.walk(foldername):

print root,dirs,files

# 篩選空目錄

empty_dirs.extend(dir for dir in dirs if os.listdir(join(root,dir))==)

for file in files:

zip.write(join(root,file).decode("gbk"))

for dir in empty_dirs:

zip=zipfile.zipfile(join(root,dir).decode("gbk"+"/"))

zip.writestr(zip)

zip.close()

print 'finish compressing %s' %zipname

if __name__=="__main__":

foldername = 'd:\python-coding\websp'

zipname = 'd:\python-coding\websp.zip'

zipfolder(foldername,zipname)

執行結果:

c:\python27\python.exe c:/users/gumengkai/pycharmprojects/untitled/zip.py

d:\python-coding\websp

finish compressing d:\python-coding\websp.zip

process finished with exit code 0

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...

VclZip壓縮資料夾

壓縮指定路徑myzipdir下的資料夾b及b目錄下的所有檔案和檔案b.txt function zipdir zipmode integer zipcontrol tvclzip myzipname,myzipdir string boolean begin result false trywith...