0

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

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 2
    Can you please share your code? Are you able to zip files with non dynamic name or do you want someone to write that code as well for you? – DevB2F Dec 19 '17 at 20:07
  • Welcome to [SO]! Stack Overflow is a question-and-answer site. At [SO], readers, such as yourself, ask questions while other readers try to answer those questions. Your post has a lot of good information, but it is missing the one essential ingredient: a question! What, precisely, are you asking? (By the way, please visit take the [tour] and read [ask] when you have a moment.) – Robᵩ Dec 19 '17 at 20:09
  • See this: https://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python?noredirect=1&lq=1 – Ashutosh Bharti Dec 19 '17 at 20:53

1 Answers1

0

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()
Gozy4
  • 444
  • 6
  • 11