## usage...
## v0.3
## Programmed : 12:54 PM 1/9/06
## Author : Fedmich
##-----
##from FedZip import *
##
##F = FedZip()
##
##src = r"D:\source directory"
##F.ZipFilename = r"c:\Fed.zip"
##F.ZipFolder(src) #would return 1 if successful...
## another usage
##F = FedZip()
##F.ZipFilename = r"C:\Fed.zip"
##
####F.AddFileToProcess(r"D:\Fed\Fed.pdf")
####F.AddFileToProcess(r"D:\Fed") # will include all the subdirectories
##
##print F.Zip(0) #returns 1 if success
import os
import glob
import zipfile
output = []
todo = []
def processDir(dir):
for path in os.listdir(dir):
fullpath = os.path.join(dir, path)
if not os.path.isdir(fullpath):
output.append( fullpath )
else:
todo.append(fullpath)
if len(todo) <> 0:
currenttodo = todo[0]
todo.pop(0)
processDir( currenttodo )
def FindFile(path):
output = []
if os.path.isdir(path):
for walk in os.walk(path):
for curFile in walk[2]:
output.append( "%s\%s" % (walk[0] , curFile) )
else:
for file in glob.glob(path):
output.append( file)
return output
class FedZip:
def __init__(self):
self.ZipFilename = ""
self.FilesToProcess = []
def ZipFolder(self, dir):
if self.ZipFilename == "":
print "Please provide a ZipFilename first!"
return
processDir(dir)
if len(output) == 0:
return 0
myZipFile = zipfile.ZipFile(self.ZipFilename, "w" )
for path in output:
ArcName = path.replace( dir + os.path.sep, "")
myZipFile.write(path, ArcName, zipfile.ZIP_DEFLATED )
print "Zipping... %s" % ArcName
myZipFile.close()
return 1
def AddFileToProcess(self, path):
self.FilesToProcess.append(path)
def Zip(self, silent=1):
if len(self.FilesToProcess) == 0:
print "No file to process..."
return 0
myZipFile = zipfile.ZipFile(self.ZipFilename, "w" )
dir = os.path.dirname( self.ZipFilename )
num_Succes = 0
totalfiles = 0
for toProcess in self.FilesToProcess:
for file in FindFile(toProcess):
barefile = os.path.basename (file)
ArcName = file.replace(dir + "\\" , "")
if ArcName == file:
ArcName = barefile
if not silent:
print "Zipping... %s" % ArcName ,
totalfiles += 1
myZipFile.write(file, ArcName, zipfile.ZIP_DEFLATED )
num_Succes +=1
if not silent:
print "Ok"
myZipFile.close()
if totalfiles == num_Succes:
return 1
else:
return 0