Python Forum

Full Version: python zipfile.ZipFile makes zip file but can't add folders to them
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to use zipfile.ZipFile to create a zip file based on folders in a main path and then send those folders to their respective zip files. The zip files are being created but when I try using write(input, 'a') nothing is added to the zip file:
    import zipfile as zp 
    import os
    
    
    # main directory containing folders to be zipped and archived
    mDir =  r"P:\2018"
    
    # ouput archive directory to conatin compressed zip files
    oDir = r" P:\2018\Archive"
    
    # get list of folders to archive
    inlst = os.listdir(mDir)
    
    # exclude the Archive folder from inlst
    inlst = inlst[1:]
    
    # loop through the list of folders
    
    for folder in inlst:
    	name = os.path.join(oDir, ("{0}{1}".format(folder,".zip")))
     	inP = os.path.join(mDir,folder)
    
     	# make a zip archive for each folder in mDir to go into the "Archive" folder
    
    	with zp.ZipFile(name,'w') as myzip:
    		myzip.write(inP)
    
    	# add current folder to current zip archive that was just creted in previous step

        with zp.ZipFile(name,'a') as myzip:
    		myzip.write(inP)
I'm writing this to automate some house cleaning and save space without deleting anything in case we ever need to retrieve a folder. It's my first time working with zipfile so I'm sure I'm missing something. My thought was it works similar to open(file, 'w') as f, f.write("something") where I'm creating a new file with 'w' and then adding to it with 'a'.

Please tell what I'm missing so I can add the folders to the respective zip files or if I'm going at this the wrong way.
Is this join statement correct? (look like 'folder' should be replaced with 'name')
inP = os.path.join(mDir,folder)
yes. it is correct. i'm now getting a new error, however:

Error:
Traceback (most recent call last): File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 323, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 654, in run exec cmd in globals, locals File "N:\Common\Script\Drivers\make_zips.py", line 1, in <module> import zipfile as zp File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__ self.fp = open(file, modeDict[mode]) IOError: [Errno 22] invalid mode ('rb') or filename: ' P:\\2018\\Archive\\CO_001_Model.zip'
Thank you Buran. Is there away to edit my post so I could have included the traceback?