Python 将多个目录压缩为一个 zip 文件 [英] Python zip multiple directories into one zip file

查看:31
本文介绍了Python 将多个目录压缩为一个 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个顶级目录 ds237,它下面有多个子目录,如下所示:

I have a top directory ds237 which has multiple sub-directories under it as below:

ds237/
├── dataset_description.json
├── derivatives
├── sub-01
├── sub-02
├── sub-03
├── sub-04
├── sub-05
├── sub-06
├── sub-07
├── sub-08
├── sub-09
├── sub-10
├── sub-11
├── sub-12
├── sub-13
├── sub-21
├── sub-22
├── sub-23
├── sub-24
├── sub-25
├── sub-26
├── sub-27
├── sub-28
├── sub-29

我正在尝试根据 zip 文件的大小从 ds237 创建多个 zip 文件(具有正确的 zip 名称).sub01-01.zip:包含sub-01到sub-07sub08-13.zip : 包含 sub08 到 sub-13

I am trying to create multiple zip files(with proper zip names) from ds237 as per size of the zip files. sub01-01.zip: contain sub-01 to sub-07 sub08-13.zip : it contains sub08 to sub-13

我编写了一个逻辑来创建子目录列表 [sub-01,sub-02, sub-03, sub-04, sub-05].我已经创建了列表,以便列表中所有子目录的总大小不应 > 5gb.

I have written a logic which creates a list of sub-directories [sub-01,sub-02, sub-03, sub-04, sub-05]. I have created the list so that the total size of the all subdirectories in the list should not be > 5gb.

我的问题: 是如何编写函数将这些子目录(在列表中)压缩到具有适当名称的目标 zip 文件中.基本上我想写一个函数如下:

My question: is how can I write a function to zip these sub-dirs (which are in a list) into a destination zip file with a proper name. Basically i want to write a function as follows:

def zipit([子目录列表], 'path/to/zipfile/sub*-*.zip'):

我在 Linux 上通常通过以下方式实现:

I Linux I generally achieve this by:

'zip -r compress/sub01-08.zip ds237/sub-0[1-8]'

推荐答案

https://stackoverflow.com/a/1855118/375530,您可以重复使用该答案的功能将目录添加到 ZipFile.

Looking at https://stackoverflow.com/a/1855118/375530, you can re-use that answer's function to add a directory to a ZipFile.

import os
import zipfile


def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file),
                       os.path.relpath(os.path.join(root, file),
                                       os.path.join(path, '..')))


def zipit(dir_list, zip_name):
    zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    for dir in dir_list:
        zipdir(dir, zipf)
    zipf.close()

zipit 函数应该使用您的预分块列表和给定名称来调用.如果您想使用程序化名称(例如 "path/to/zipfile/sub{}-{}.zip".format(start, end)),您可以使用字符串格式.

The zipit function should be called with your pre-chunked list and a given name. You can use string formatting if you want to use a programmatic name (e.g. "path/to/zipfile/sub{}-{}.zip".format(start, end)).

这篇关于Python 将多个目录压缩为一个 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆