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):
        StringIO.__init__(self)
        self.capacity = capacity
        self.check()

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

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

    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
zipf.close()

''' my output
Traceback (most recent call last):
  File "Documents/crazip.py", line 27, in <module>
    zipf.write("/home/eric/foo.ps")
  File "/usr/lib/python2.7/zipfile.py", line 1169, in write
    self.fp.write(buf)
  File "Documents/crazip.py", line 12, in write
    self.check()
  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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.