I am still new to programming and hoping someone can point me in the best direction.

I am creating a script that monitors a directory and creates a zip file and then mails the archive. I have successfully monitored the dir and can zip the files. I am somewhat lost on what the best approach would be to assure the archive is 3MB or less. I was thinking check file size of x files and then create the zip file. Once the zip was created check the size and if needed remove files.

Something tells me I am thinking to complicated and a better way is out there. I have checked google but didn't come across anything other than check the size of the zip.

I should mention files may be dropped in the directory by the hundreds.

I will apologize in advance if I missed something in my searchers or it is obvious.

I managed to fool the zipfile module by using a StringIO as output file:

from StringIO import StringIO

class Crazip(StringIO):
    def __init__(self, capacity):
        self.capacity = capacity

    def write(self, data):
        StringIO.write(self, data)

    def writelines(self, lines):
        for x in lines:

    def check(self):
        if self.tell() > self.capacity:
            raise RuntimeError("Zip capacity exceeded")

from zipfile import ZipFile
KB = 1024
MB = 1024 * KB

MAX = 1 * KB # replace with 3 * MB
FILENAME = "/home/eric/foo.ps"

ofh = Crazip(MAX)
zipf = ZipFile(ofh, 'a')
zipf.write(FILENAME) # Add one or more files to the archive

''' my output
Traceback (most recent call last):
  File "Documents/crazip.py", line 27, in <module>
  File "/usr/lib/python2.7/zipfile.py", line 1169, in write
  File "Documents/crazip.py", line 12, in write
  File "Documents/crazip.py", line 20, in check
    raise RuntimeError("Zip capacity exceeded")
RuntimeError: Zip capacity exceeded
Exception RuntimeError: RuntimeError('Zip capacity exceeded',) in <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0x8e1f60c>> ignored

You should be able to create the archive in memory with this technique. If it works, simply write the contents of the StringIO to a file.

This question has already been answered. Start a new discussion instead.