其他
Mxd批量裁剪Python代码
The following article is from gisoracle Author 闫磊ArcGIS
#coding=utf8
import arcpyimport os
from arcpy import env
import math
def ConverttoStr(v):
if type(v)==str:
return v
else:
return str(v)
def geotoPolygon(geometry):
part_count = geometry.partCount #有几部分
array = arcpy.Array()
#arcpy.AddMessage("FID:"+str(FID)+",part_count:"+str(part_count))
for j in range(part_count):
partgeometry=geometry.getPart(j)
num=partgeometry.count
for k in range(num):
pt=partgeometry[k]
point = arcpy.Point(pt.X,pt.Y)
array.add(point)
bPolygon = arcpy.Polygon(array)
return bPolygon
env.overwriteOutput = True
LayerName = arcpy.GetParameterAsText(0) #图层
FieldName = arcpy.GetParameterAsText(1) #字段
outPath= arcpy.GetParameterAsText(2) #输出路径
outLX = arcpy.GetParameterAsText(3) #输出数据库类型
desc = arcpy.Describe(LayerName)
if desc.shapeType!="Polygon":
arcpy.AddMessage(LayerName+"不是面层")
pass
shapeName = desc.shapeFieldName
oldpath=desc.path.lower()
#arcpy.AddMessage("desc.dataType:"+desc.dataType+",oldpath:"+oldpath)
if desc.dataType.startswith("Feature"):#看是否有数据集FeatureLayer,FeatureClass,数据ShapeFile是shp
if oldpath.index(".")>0:
if not oldpath.endswith(".mdb"):
if not oldpath.endswith(".gdb"):
p=oldpath.rindex("\\")
#arcpy.AddMessage("p================:"+str(p)+"")
if p<0:
p=oldpath.rindex("/")
oldpath=oldpath[0: p]
arcpy.AddMessage("oldpath:"+oldpath+"")
if oldpath.endswith(".mdb"):
oldlx="ACCESS_WORKSPACE"
elif oldpath.endswith(".gdb"):
oldlx="FILEGDB_WORKSPACE"
else:
oldlx="SHAPEFILE_WORKSPACE"
OIDField=desc.OIDFieldName
#mxd = arcpy.mapping.MapDocument("CURRENT")
rows = arcpy.SearchCursor(LayerName)
try:
for row in rows:
try:
geo = row.getValue(shapeName)
FID=row.getValue(OIDField)
arcpy.AddMessage("FID:"+ConverttoStr(FID))
bPolygon = geotoPolygon(geo)
objv=row.getValue(FieldName)
FieidValue=ConverttoStr(objv)
gdb=".gdb"
gdblx="FILEGDB_WORKSPACE"
if outLX.endswith("MDB"):
gdb=".mdb"
gdblx="ACCESS_WORKSPACE"
out_mdb=outPath+"\\"+FieidValue+gdb
if not arcpy.Exists(out_mdb):
if outLX.endswith("GDB"):
arcpy.CreateFileGDB_management(os.path.dirname(out_mdb),os.path.basename(out_mdb))
else:
arcpy.CreatePersonalGDB_management(os.path.dirname(out_mdb),os.path.basename(out_mdb))
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):
arcpy.Clip_analysis(lyr, bPolygon,out_mdb+"\\"+ lyr.name, "")
arcpy.AddMessage("lyr.name:"+out_mdb+"\\"+ lyr.name)
mypath=oldpath #mxd.filePath是mxd文件路径
arcpy.AddMessage("mypath:"+ConverttoStr(mypath)+",out_mdb="+out_mdb+","+gdblx+","+oldlx)
mxd.replaceWorkspaces(mypath,oldlx,out_mdb,gdblx)
mxd.saveACopy(outPath+"\\"+FieidValue+".mxd")
except Exception as err:
arcpy.AddError(err.message)
finally:
if mxd:
del mxd
文章授权赚钱:gisoracle
- END -