How to create a zip archive of a directory in Python?

后端 未结 25 2628
暗喜
暗喜 2020-11-22 07:12

How can I create a zip archive of a directory structure in Python?

25条回答
  •  既然无缘
    2020-11-22 07:53

    To give more flexibility, e.g. select directory/file by name use:

    import os
    import zipfile
    
    def zipall(ob, path, rel=""):
        basename = os.path.basename(path)
        if os.path.isdir(path):
            if rel == "":
                rel = basename
            ob.write(path, os.path.join(rel))
            for root, dirs, files in os.walk(path):
                for d in dirs:
                    zipall(ob, os.path.join(root, d), os.path.join(rel, d))
                for f in files:
                    ob.write(os.path.join(root, f), os.path.join(rel, f))
                break
        elif os.path.isfile(path):
            ob.write(path, os.path.join(rel, basename))
        else:
            pass
    

    For a file tree:

    .
    ├── dir
    │   ├── dir2
    │   │   └── file2.txt
    │   ├── dir3
    │   │   └── file3.txt
    │   └── file.txt
    ├── dir4
    │   ├── dir5
    │   └── file4.txt
    ├── listdir.zip
    ├── main.py
    ├── root.txt
    └── selective.zip
    

    You can e.g. select only dir4 and root.txt:

    cwd = os.getcwd()
    files = [os.path.join(cwd, f) for f in ['dir4', 'root.txt']]
    
    with zipfile.ZipFile("selective.zip", "w" ) as myzip:
        for f in files:
            zipall(myzip, f)
    

    Or just listdir in script invocation directory and add everything from there:

    with zipfile.ZipFile("listdir.zip", "w" ) as myzip:
        for f in os.listdir():
            if f == "listdir.zip":
                # Creating a listdir.zip in the same directory
                # will include listdir.zip inside itself, beware of this
                continue
            zipall(myzip, f)
    

提交回复
热议问题