I have written a solution to your problem and it is as follows:
- List all the files to compressed.
import os
import shutil
print("----PROCESS STARTED----")
filelist = [] #list of files to be compressed
filegroup = set() #set for grouping files
basedir = "C:/Users/XYZ/" #base directory
extension = "jpg" #extension of the file to be compressed
extensionlen = 3 #extension length of the file to be compressed
folderstart = 0 #starting index of the
folderend = 9
#list of files to be compressed
for f in os.listdir(basedir):
if f[-extensionlen:] == extension :
filelist.append(f)
- Find the list of group in which these files can be grouped.
#list of groups
for file in filelist:
filegroup.add(file[folderstart:folderend])
print(file)
- Create the folder for these groups.
#create folder for the group
for group in filegroup:
print(group)
if not os.path.isdir(basedir+group) :
os.mkdir(basedir+group)
- Move the files to corresponding folders.
#move files to the folders
for file in filelist:
os.rename(basedir+file,basedir+file[folderstart:folderend]+"/"+file)
- Compress the folders.
#compress the folders
for group in filegroup:
shutil.make_archive(basedir+group, 'zip', basedir+group)
shutil.rmtree(basedir+group)
print("----PROCESS COMPLETED----")
Complete solution.
import os
import shutil
print("----PROCESS STARTED----")
filelist = [] #list of files to be compressed
filegroup = set() #set for grouping files
basedir = "C:/Users/XYZ/" #base directory
extension = "jpg" #extension of the file to be compressed
extensionlen = 3 #extension length of the file to be compressed
folderstart = 0
folderend = 9
#list of files to be compressed
for f in os.listdir(basedir):
if f[-extensionlen:] == extension :
filelist.append(f)
#list of groups
for file in filelist:
filegroup.add(file[folderstart:folderend])
print(file)
#create folder for the group
for group in filegroup:
print(group)
if not os.path.isdir(basedir+group) :
os.mkdir(basedir+group)
#move files to the folders
for file in filelist:
os.rename(basedir+file,basedir+file[folderstart:folderend]+"/"+file)
#compress the folders
for group in filegroup:
shutil.make_archive(basedir+group, 'zip', basedir+group)
shutil.rmtree(basedir+group)
print("----PROCESS COMPLETED----")
I have tested this solution and it works. I have added some more features to this code for my use. This solution can be used to compress images, text files, etc.