(十八)arcpy开发&利用arcpy实现在arcgis中对字段的删除

本节,我们将带领大家一起来学习一下关于字段删除方面的函数。我们将会删除字段中除了FID shape外的其他字段。其中利用到函数字段列举函数。arcpy.ListField,下面定义的这个函数将返回所有的字段。

def getFieldNames( fc):

        fieldList = []
        for f in arcpy.ListFields(fc):
            fieldList.append(str(f.name))
        return fieldList

其中还有关于字段方面的函数是字段必须属性,required,我们使用这个属性来保留必须的字段。具体的使用函数如下所示。

def getFieldNamesRequired( fc, req):

        fieldList = []
        fieldObjList = arcpy.ListFields(fc)
        for f in fieldObjList:
            if f.required == req:
                fieldList.append(f.name)
        return fieldList

很多时候,我们处理shapefile数据还要判断数据是否是锁定了,下面的函数arcpy.TestSchemaLock就是用来判断函数是否为锁定了。

def isLocked(obj, datatype):

    if arcpy.TestSchemaLock(obj):
        logger.p5("The %s is unlocked: can be overwritten, deleted, or modified." % datatype)
        return True
    else:
        logger.p3("The %s is LOCKED" % datatype)
        return False
经过上面的函数说明后,我们来看一下完整的实现代码。具体如下所示。
#coding=utf-8
import logging
import logs
import os
import arcpy
logger = logs.ArcLogger()
logging.basicConfig()


def isLocked(obj, datatype):

    if arcpy.TestSchemaLock(obj):
        logger.p5("The %s is unlocked: can be overwritten, deleted, or modified." % datatype)
        return True
    else:
        logger.p3("The %s is LOCKED" % datatype)
        return False

def checkFileGDBIntegrity( path):
        if os.path.exists(path) or path == 'in_memory':
            logger.p5("GDB folder: OK,", )
            if arcpy.Describe(path).dataType in ['Workspace','Folder','FeatureDataset','FileSystem']:
                logger.p5("%s integrity: OK" % arcpy.Describe(path).dataType)
                return True
            else:
                logger.p3("The folder is not a real GDB or the GDB is corrupted.")
                return False
        else:
            logger.p3("Folder %s does not exist." % path)
            return False

def setEnvVars( workGDB, overwrite, Z, M, XYtol):

        logger.p5("Setting environment variables...")

        if not checkFileGDBIntegrity(workGDB):
            logger.p2("No valid file GDB workspace.")
            return False

        arcpy.env.workspace = workGDB

        arcpy.env.overwriteOutput = overwrite

        arcpy.env.outputZFlag = Z
        arcpy.env.outputMFlag = M

        if type(XYtol) is str and XYtol.endswith("Meters"):
            XYtol = float(XYtol.split(' ')[0])

        if XYtol == 'DEFAULT':
            XYtol = "0.001 Meters"
            XYres = "0.0001 Meters"
        else:

            XYres = XYtol / 10
            # Put the value into a string ending " Meters"
            XYtol = "%s Meters" % XYtol
            XYres = "%s Meters" % XYres
        arcpy.env.XYTolerance = XYtol
        arcpy.env.XYResolution = XYres

        logger.p5("Confirming environment settings:")
        logger.p5("Workspace: %s" % arcpy.env['workspace'])
        logger.p5("Overwrite:%s. Z geom:%s. M geom:%s. XY tolerance:%s. XY resolution:%s." % (
            arcpy.env['overwriteOutput'],arcpy.env['outputZflag'],
            arcpy.env['outputMflag'],arcpy.env['XYTolerance'],arcpy.env['XYResolution']))
        pass

def getFieldNames( fc):

        fieldList = []
        for f in arcpy.ListFields(fc):
            fieldList.append(str(f.name))
        return fieldList

def getFieldNamesRequired( fc, req):

        fieldList = []
        fieldObjList = arcpy.ListFields(fc)
        for f in fieldObjList:
            if f.required == req:
                fieldList.append(f.name)
        return fieldList

def fcAvailable( fc):

        if not arcpy.Exists(fc):
            arcpy.AddMessage("Feature class %s does not exist." % os.path.basename(fc))
            return False


        basePath = os.path.dirname(fc)


        setEnvVars(basePath,True,'Disabled','Disabled','DEFAULT')
        return isLocked(fc, 'feature class')

def deleteFields(fc, action, fieldList):

    try:
        fcName = os.path.basename(fc)
    except:
        fcName = fc
    if not fcAvailable(fc):
        logger.p2("Cannot delete fields because this feature class is locked.")
        return False
    fieldsToDelete = []

    fields = getFieldNames(fc)


    reqFields = getFieldNamesRequired(fc, True)
    for f in reqFields:
        fields.remove(f)


    if fieldList == 'ALL' and action == 'DEL':

        fieldsToDelete = fields
    elif fieldList == 'ALL' and action == 'KEEP':
        fieldsToDelete = []
    elif action == 'DEL' and type(fieldList) is list:
        fieldsToDelete = fieldList
    elif action == 'KEEP' and type(fieldList) is list:

        for fieldToSkip in fieldList:

            if fieldToSkip in fields:
                fields.remove(fieldToSkip)
        fieldsToDelete = fields


    if len(fieldsToDelete) == 0:
        logger.p3("%s: No fields to delete." % fcName)
        return False


    for f in fieldsToDelete:
        if f not in fields:
            logger.p3("Field %s does not exist." % f)
            fieldsToDelete.remove(f)


    print("%s: Deleting fields: %s" % (fcName, fieldsToDelete))
    try:
        arcpy.DeleteField_management(fc, fieldsToDelete)
        return True
    except:
        logger.p2("Couldn't delete fields!")
        return False


deleteFields(r"D:\\Data\\中国国界和省界的SHP格式数据\\省界\\bou2_4p.shp",'DEL','ALL');

                                                                                更多内容,请关注公众号

                                                                     

转载自:https://blog.csdn.net/u010608964/article/details/87815681

You may also like...