How do I zip the contents of a folder using python (version 2.5)?

前端 未结 3 966
闹比i
闹比i 2020-12-02 11:39

Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go

相关标签:
3条回答
  • 2020-12-02 12:13

    On python 2.7 you might use: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]).

    base_name archive name minus extension

    format format of the archive

    root_dir directory to compress.

    For example

     shutil.make_archive(target_file, format="bztar", root_dir=compress_me)    
    
    0 讨论(0)
  • 2020-12-02 12:16

    Adapted version of the script is:

    #!/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)
    

    Example:

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

    It creates 'C:\zipdir\test.zip' archive with the contents of the 'c:\tmp\test' directory.

    0 讨论(0)
  • 2020-12-02 12:16

    Here is a recursive version

    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()
    
    0 讨论(0)
提交回复
热议问题