Python用动态名称压缩文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python用动态名称压缩文件相关的知识,希望对你有一定的参考价值。

美好的一天,我有一个包含12个文件的目录。我想创建4个单独的zip文件,每个文件包含3个文件。我想根据文件名动态命名zip文件。 (每个拉链的所有3个开始时都相同)

即。

IT-12123.txt
IT-12123.pdf
IT-12123.xls

IT-23232.txt
IT-23232.pdf
IT-23232.xls

我想创建IT-23232.zip(包含该zip文件中的所有文件)还有一个名为IT-12123.zip的zip文件(该zip文件中包含所有这些文件)

谢谢

答案

如果您的文件都位于同一文件夹中,这是一个简单的解决方案。

import itertools
import glob
import os
import zipfile 
# move to the directory where the files are located
os.chdir("/mydir")
# find all files starting with IT
files = glob.glob('IT*')
files_no_ext = []
for file in files:
    # remove extension from files names
    files_no_ext.append(os.path.splitext(file)[0])
# group no extension files by name
grouped_files= itertools.groupby(files_no_ext)
for name, group in grouped_files:
    zipped = zipfile.ZipFile(name+'.zip', 'w')
    to_zip = glob.glob(name+'*')
    for file in to_zip:
        zipped.write(file)
    zipped.close()

以上是关于Python用动态名称压缩文件的主要内容,如果未能解决你的问题,请参考以下文章

用 Python 管理压缩包,压缩文件一找就出现

python python zipfile获取并解压缩片段

spdy3 的名称/值块有时无法用 python 解压缩

在ansible模板中使用动态组名称

用 Python 管理压缩包

用python解压图片并打印代码