[886] Some useful functions in ArcPy

发布时间 2023-09-25 15:24:32作者: McDelfino

Exists: Determines the existence of the specified data object. This function tests for the existence of various data types including feature classes, tables, datasets, shapefiles, workspaces, layers, and files. The function returns a Boolean indicating whether the element exists.

查看代码
 import arcpy
arcpy.env.workspace = r'C:\Path\to\Your\Geodatabase.gdb'  # Replace with the actual workspace path
feature_class_name = 'YourFeatureClass'  # Replace with the actual feature class name
if arcpy.Exists(feature_class_name):
    print(f"The feature class '{feature_class_name}' exists.")
else:
    print(f"The feature class '{feature_class_name}' does not exist.")

Create File Geodatabase (Data Management): Creates a file geodatabase in a folder.

查看代码
 import arcpy
arcpy.env.workspace = r'C:\Path\to\Your\Folder'
geodatabase_name = 'YourGeodatabase.gdb'  # Replace with your desired geodatabase name
arcpy.CreateFileGDB_management(arcpy.env.workspace, geodatabase_name)

ListFeatureClasses: Returns a list of the feature classes in the current workspace, limited by name, feature type, and optional feature dataset.

查看代码
 import arcpy
arcpy.env.workspace = r"C:\path\to\your\geodatabase.gdb"
feature_classes = arcpy.ListFeatureClasses()

Merge (Data Management): Combines multiple input datasets into a single, new output dataset. This tool can combine point, line, or polygon feature classes or tables.

Clip (Analysis): Extracts input features that overlay the clip features.

Multiple Ring Buffer (Analysis): Creates multiple buffers at specified distances around the input features. These buffers can be merged and dissolved using the buffer distance values to create non-overlapping buffers.

SearchCursor: Establishes read-only access to the records of a feature class or table. It returns an iterator of tuples. The order of values in the tuple matches the order of fields specified by the field_names argument.

查看代码
 import arcpy
arcpy.env.workspace = r'C:\Path\to\Your\Workspace'
shapefile_name = 'your_shapefile.shp'  # Replace with the actual shapefile name

with arcpy.da.SearchCursor(shapefile_name, ['SHAPE@', 'FIELD1', 'FIELD2']) as cursor:
    for row in cursor:
        geometry = row[0]  # Access the geometry of the feature
        field1_value = row[1]  # Access the value of FIELD1
        field2_value = row[2]  # Access the value of FIELD2
        print(f"Geometry: {geometry}, FIELD1: {field1_value}, FIELD2: {field2_value}")