python压缩多个文件_Python将多个目录压缩为一个zip文件

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

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

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.

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([list of subdirs], 'path/to/zipfile/sub*-*.zip'):

I Linux I generally achieve this by:

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

解决方案

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()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值