2008-11-17 96 views
27

一旦我在特定文件夾中具有所有需要的文件,我想讓我的python腳本壓縮文件夾內容。如何使用python(版本2.5)壓縮文件夾的內容?

這可能嗎?

我該怎麼去做呢?

+0

答案,對於現代的Python,是在[此處](http://stackoverflow.com/q/1855095/541136) – 2017-03-14 19:08:00

回答

31

改編的the script版本是:

#!/usr/bin/env python 
from __future__ import with_statement 
from contextlib import closing 
from zipfile import ZipFile, ZIP_DEFLATED 
import os 

def zipdir(basedir, archivename): 
    assert os.path.isdir(basedir) 
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z: 
     for root, dirs, files in os.walk(basedir): 
      #NOTE: ignore empty directories 
      for fn in files: 
       absfn = os.path.join(root, fn) 
       zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path 
       z.write(absfn, zfn) 

if __name__ == '__main__': 
    import sys 
    basedir = sys.argv[1] 
    archivename = sys.argv[2] 
    zipdir(basedir, archivename) 

例子:

C:\zipdir> python -mzipdir c:\tmp\test test.zip 

它創建'C:\zipdir\test.zip'歸檔與'c:\tmp\test'目錄的內容。

+0

`ZFN = absfn [長度(BASEDIR)+ LEN (os.sep):]`爲什麼不是`absbasedir = os.path.abspath(basedir); os.path.relpath(absfn,absbasedir)`?另外,basedir和os.sep的長度可以看作是不變的,所以它應該在兩個for循環之外。 – n611x007 2013-08-16 13:11:49

5

這裏是一個遞歸版本

def zipfolder(path, relname, archive): 
    paths = os.listdir(path) 
    for p in paths: 
     p1 = os.path.join(path, p) 
     p2 = os.path.join(relname, p) 
     if os.path.isdir(p1): 
      zipfolder(p1, p2, archive) 
     else: 
      archive.write(p1, p2) 

def create_zip(path, relname, archname): 
    archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED) 
    if os.path.isdir(path): 
     zipfolder(path, relname, archive) 
    else: 
     archive.write(path, relname) 
    archive.close() 
相關問題