I’m trying to write a Python script which compress xml
files.
E.g. If the xml files are 28 and I set file_limit
to 10, it should create 4 zipped files: Part_1.zip
which include the first 10 files, Part_2.zip
which include the seconds 10, Part_3.zip
which include the last 8 files.
Furthermore, if I set size_limit
to 2000 Byte and each file is 500 Byte it should zip just 4 files.
This is what I done but I cannot understand why the for loop doesn’t continue after the first zip creation.
import fnmatch
import os
import zipfile
files_limit = 10
size_limit = 200000
def compress(file_names, zip_name):
compression = zipfile.ZIP_DEFLATED
zf = zipfile.ZipFile(zip_name, mode="w")
try:
for file_name in file_names:
zf.write(file_name, file_name, compress_type=compression)
except FileNotFoundError:
print("An error occurred")
finally:
zf.close()
dir = os.listdir(os.getcwd())
files = fnmatch.filter((dir),'*.xml')
num_files = len(fnmatch.filter(dir,'*.xml'))
chunks = []
part_num = 1
total_size = 0
for file in files:
total_size += os.path.getsize(file)
chunks.append(files.pop())
if(total_size > size_limit) or (len(chunks) >= files_limit):
compress(chunks, "Part_" + str(part_num) + ".zip")
chunks.clear()
total_size = 0
part_num +=1