I need to take a folder that contains multiple shapefiles and then zip them all into their own individual zip file. I found this script on a REALLY old post and it does what I'm looking for. However, I'm running into one issue. Before the zip section of the script, the python steps through several other steps of the shapefiles being exported to this location with certain criteria. So what happens is I get the shapefiles, but each shapefile contains a lock file. When the script starts for the zip, it starts to execute from top to bottom in the folder, but once it hits the first lock file it then fails. I have this in Notebook in a Pro Project. Once I close the Pro Project the lock files disappear, but as soon as I reopen the Pro Project the lock is reapplied because even though I don't have a map open, when I run my export features script it automatically adds it to the default map so it places a lock on it. Is there a way to make the below zip script ignore any lock files or release all shapefile lock files in a folder?
import arcpy, os
from os import path as p
import zipfile
arcpy.overwriteOutput = True
def ZipShapes(path, out_path):
arcpy.env.workspace = path
shapes = arcpy.ListFeatureClasses()
# iterate through list of shapefiles
for shape in shapes:
name = p.splitext(shape)[0]
print (name)
zip_path = p.join(out_path, name + '.zip')
zip = zipfile.ZipFile(zip_path, 'w', compression=zipfile.ZIP_DEFLATED)
zip.write(p.join(path,shape), shape)
for f in arcpy.ListFiles('%s*' %name):
if not f.endswith('.shp'):
zip.write(p.join(path,f), f)
print ("All files written to %s" %zip_path)
zip.close()
if __name__ == '__main__':
path = r"Z:\General\Projects\Engineering\SubSurface Mapping\DataExport\Updates"
outpath = r"Z:\General\Projects\Engineering\SubSurface Mapping\DataExport\Updates\ZipFiles"
ZipShapes(path, outpath)
Solved! Go to Solution.
try changing line 19 to
if not f.endswith(('.lock', '.shp')):
That will make it ignore ".shp" and lock files
try changing line 19 to
if not f.endswith(('.lock', '.shp')):
That will make it ignore ".shp" and lock files
I get the below when I change that line of code.
They need to be wrapped in two parentheses: One for the endswith() and the other to feed both of them to the endswith() at the same time.
if not f.endswith(('.lock', '.shp')):
not
if not f.endswith('.lock', '.shp'):
Right now it thinks you fed it two arguments when you're really trying to feed it one.
Missed the double brackets. on your first post. That worked!!! Thank you!
You can also config Pro to Not add the output layers to the map, then shouldn't lock them. (not tested with shapefiles).
Could also just run it standalone outside of Pro.
R_