python 实现文件的n等份批量压缩为.zip格式

import zipfile
import time

# 读入待文件路径
img_dir = r'/Users/Documents/Secondar/'

# arr是被分割的list,n是每个chunk中含n元素。
def chunks(arr, n):
    return [arr[i:i+n] for i in range(0, len(arr), n)]
# 批量读入文件list
file_list = []
for file in os.listdir(img_dir):
    if file.endswith('.jpg'):  
        file_list.append(file)
print("总的文件数量:", len(file_list))

# 切分文件集为4等分,准备压缩
file_list_split = chunks(file_list, 4000)
print("切分的总份数:", len(file_list_split))
# 开始压缩
for i in range(len(file_list_split)):
    print("epoch:",i)
    # 定义压缩的title和准备文件
    compressPathName = img_dir + 'train_img_part0' + str(i) +'.zip'
    zip_x = zipfile.ZipFile(compressPathName, 'w', zipfile.ZIP_DEFLATED)
    for j in range(len(file_list_split[i])):
        file_tmp = file_list_split[i][j]
        file_path = os.path.join(img_dir, file_tmp)
        zip_x.write(file_path, file_tmp)
    zip_x.close()
    time.sleep(5)
    print('压缩完成')

猜你喜欢

转载自blog.csdn.net/weixin_42782150/article/details/114409477