Good day, I have a directory with 12 files. I would like to create 4 separate zip files with 3 files in each. The hitch is I would like to dynamically name the zip file based on the file names. (All 3 for each zip start off the same)
ie.
IT-12123.txt
IT-12123.pdf
IT-12123.xls
IT-23232.txt
IT-23232.pdf
IT-23232.xls
I would like to create IT-23232.zip (with all of those files in that zip) also a zip called IT-12123.zip (with all of those files in that zip)
Thank you
Here is a simple solution if your files are all located in the same folder.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.