python批量为指定文件夹下的shp添加XY字段并计算几何信息

时间:2024-03-30 17:09:20

import arcpy
import os 

def CalcXY(dir):
    try:
        print ("Set Env")
        arcpy.env.workspace = './'+dir

        print ("Start AddField And Calculate BeginID")        

        shps = arcpy.ListFiles("Rivl.shp")

        for shp in shps:
            fieldList = arcpy.ListFields(shp,"","Double")
            fieldNames = []
            for field in fieldList:
                fieldNames.append(field.name)
            if "X" not in fieldNames:
                arcpy.AddField_management(shp,"X","DOUBLE",20,5)
                arcpy.AddField_management(shp,"Y","DOUBLE",20,5)                
                arcpy.CalculateField_management(shp, "X", "!SHAPE.CENTROID.X!","PYTHON_9.3")
                arcpy.CalculateField_management(shp, "Y", "!SHAPE.CENTROID.Y!","PYTHON_9.3")
                print (shp)

        print ("AddField And Calculate BeginID End")
    except Exception as e:
        print (e.message)
        CalcXY()

file_dir="."
for root, dirs, files in os.walk(file_dir):
    arcpy.AddMessage("cdir"+root)
    if dirs:
        num=len(dirs)
        arcpy.AddMessage("cdir"+str(num))
        for i in range(num):
            #arcpy.AddMessage("cdir"+dirs[i])
            print (dirs[i])
            CalcXY(dirs[i])
执行效果:

python批量为指定文件夹下的shp添加XY字段并计算几何信息

感谢支持技术分享,请扫码点赞支持:

技术合作交流qq:2401315930

python批量为指定文件夹下的shp添加XY字段并计算几何信息

python批量为指定文件夹下的shp添加XY字段并计算几何信息

python批量为指定文件夹下的shp添加XY字段并计算几何信息