在gis中常用的python代码模板

1.查询gdb格式文件内某个文件所具有的字段属性和相关类型和长度

import arcpy

 

arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"    “确定工作空间”

try:

    fieldList = arcpy.ListFields("Burglary")

    for fld in fieldList:

        print "%s is a type of %s with a length of %i" % (fld.name, fld.type, fld.length)

except Exception as e:

    print(e.message)

 

2.保存副本工程.mxd;以及更改地图文档标题

import arcpy.mapping as mapping    “引入arcpy”

mxd = mapping.MapDocument("CURRENT")     “获取当前地图文档” “也可引用绝对路径”

print(mxd.title)

mxd.title = "Copy of Crime Project"             “更改地图文档名称”

mxd.saveACopy("c:/ArcpyBook/Ch2/crime_copy.mxd") “保存工程副本”

 

  1. 限制图层框的图层数据列表

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for df in mapping.ListDataFrames(mxd):       “文本框”

    if (df.name == 'Crime'):

        layers = mapping.ListLayers(mxd,"Burg*",df) “列表函数ListLayers”“通配符Burg*”

        for layer in layers:

            print(layer.name)

 

4.缩放至所选要素

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd,"Crime")[0]

layer = mapping.ListLayers(mxd,"Burglaries*",df)[0]

df.extent = layer.getSelectedExtent()

 

 

 

import arcpy.mapping as mapping

... mxd = mapping.MapDocument("CURRENT")

... mxd.activeDataFrame.zoomToSelectedFeatures()  “当前活动的框”

 

 

 

 

 

5.定义查询

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for df in mapping.ListDataFrames(mxd):

    if (df.name == 'Crime'):

        layers = mapping.ListLayers(mxd,'Crime Density by School District',df)

        for layer in layers:

            query = '"NAME" = \'Lackland ISD\''

            layer.definitionQuery = query

            df.extent = layer.getExtent()

 

6.添加图层到数据框

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd, "Crime")[0]

layer=mapping.Layer("C:\ArcpyBook\data\School_Districts.lyr")

mapping.AddLayer(df,layer,"AUTO_ARRANGE")

 

 

7.插入图层到地图文档

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd, "Crime")[0]

refLayer = mapping.ListLayers(mxd, "Burglaries*", df)[0]

insertLayer = mapping.Layer(r"C:\ArcpyBook\data\CityOfSanAntonio.gdb\Crimes2009")

mapping.InsertLayer(df,refLayer,insertLayer,"BEFORE")

 

8.更新图层的符号系统

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd, "Crime")[0]

updateLayer = mapping.ListLayers(mxd,"Crime Density by School District",df)[0]

sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\CrimeDensityGradSym.lyr")

mapping.UpdateLayer(df,updateLayer,sourceLayer,True)

 

9.更新图层的属性

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd, "Crime")[0]

updateLayer = mapping.ListLayers(mxd,"Crimes2009",df)[0]

sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\BurglariesNoForcedEntry.lyr")

mapping.UpdateLayer(df,updateLayer,sourceLayer,False)

 

 

10.操作数据框中启用时间的图层

import arcpy.mapping as mapping, os

mxd = mapping.MapDocument("CURRENT")

df = mapping.ListDataFrames(mxd, "Crime")[0]

dft = df.time

dft.currentTime = dft.startTime

 

while dft.currentTime <= dft.endTime:

    fileName = str(dft.currentTime).split(" ")[0] + ".pdf"

    mapping.ExportToPDF(mxd,os.path.join(r"C:\ArcpyBook\Ch2", fileName))

    print "Exported " + fileName

dft.currentTime = dft.currentTime + dft.timeStepInterval

 

 

11.修复数据源

import arcpy.mapping as mapping

mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch3\Crime_BrokenDataLinks.mxd")

mxd.findAndReplaceWorkspacePaths(r"C:\ArcpyBook\Ch3\Data\OldData\CityOfSanAntonio.gdb", r"C:\ArcpyBook\Data\CityOfSanAntonio.gdb")   “被查找位置”

mxd.saveACopy(r"C:\ArcpyBook\Ch3\Crime_DataLinksFixed.mxd")

 

12.将文件地类数据库gdb 转换为个人地理数据库mdb

import arcpy.mapping as mapping

mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch3\Crime_DataLinksFixed.mxd")

mxd.replaceWorkspaces(r"c:\ArcpyBook\data\CityOfSanAntonio.gdb", "FILEGDB_WORKSPACE",r"c:\ArcpyBook\new_data\CityOfSanAntonio_Personal.mdb","ACCESS_WORKSPACE")

mxd.saveACopy(r"c:\ArcpyBook\Ch3\Crime_DataLinksUpdated.mxd")

 

13.单个图层的数据源修复

import arcpy.mapping as mapping

mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch3\Crime_DataLinksLayer.mxd")

df = mapping.ListDataFrames(mxd,"Crime")[0]

lyr = mapping.ListLayers(mxd,"Burglary",df)[0]

lyr.replaceDataSource(r"c:\ArcpyBook\data","SHAPEFILE_WORKSPACE","Burglaries_2009")

mxd.saveACopy(r"c:\ArcpyBook\Ch3\Crime_DataLinksNewLayer.mxd")

 

 

 

 

 

 

 

 

14.查找文件中所有地图文档丢失的数据源

import arcpy.mapping as mapping, os

f = open('BrokenDataList.txt', 'w')

for root, dirs, files in os.walk("c:\ArcpyBook"):

    for name in files:

        filename = os.path.join(root, name)

        if ".mxd" in filename:

            mxd = mapping.MapDocument(filename)

            f.write("MXD: " + filename + "\n")

            brknList = mapping.ListBrokenDataSources(mxd)

            for brknItem in brknList:

                print("Broken data item: " +  brknItem.name + " in " + filename)

                f.write("\t" + brknItem.name + "\n")

print("All done")

f.close()

 

 

15.输出布局元素的所有名称

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for el in mapping.ListLayoutElements(mxd):

    if el.name != "":

        print el.name

 

16.输出匹配的布局元素的名称

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for el in mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT","*Crime*"):

print el.name

 

17.更改布局元素的属性

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

elLeg = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT","*Crime*")[0]

elLeg.title = "Crimes by School District"

for item in elLeg.listLegendItemLayers():

print item.name

 

18.输出可用打印机的列表

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for printerName in mapping.ListPrinterNames():

print printerName

 

 

19.查找相应的数据框并穿到默认的打印机

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for df in mapping.ListDataFrames(mxd):

    if df.name == "Test_Performance":

        mapping.PrintMap(mxd,"",df)

 

20.将指定的数据框输出为pdf文件

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for df in mapping.ListDataFrames(mxd):

    if df.name == "Crime":

        df.referenceScale = df.scale

        mapping.ExportToPDF(mxd,r"c:\ArcpyBook\Ch4\DataFrameCrime.pdf",df)

 

21.将制定的数据框输出为jpg格式

import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")

for df in mapping.ListDataFrames(mxd):

    if df.name == "Crime":

        mapping.ExportToJPEG(mxd,r"c:\ArcpyBook\Ch4\DataFrameCrime.jpg",df)

 

22.导出报表

import arcpy

import os

 

path = os.getcwd()

 

#Create PDF and remove if it already exists

pdfPath = path + r"\CrimeReport.pdf"

if os.path.exists(pdfPath):

    os.remove(pdfPath)

pdfDoc = arcpy.mapping.PDFDocumentCreate(pdfPath)

 

districtList = ["Harlandale", "East Central", "Edgewood", "Alamo Heights", "South San Antonio", "Southside", "Ft Sam Houston","North East", "Northside", "Lackland", "Southwest", "Judson", "San Antonio"]

 

mxd = arcpy.mapping.MapDocument(path + r"\Crime_Ch4.mxd")

df = arcpy.mapping.ListDataFrames(mxd)[0]

lyr = arcpy.mapping.ListLayers(mxd, "Crime Density by School District")[0]

 

pageCount = 1

for district in districtList:

    #Generate image for each district

    whereClause = "\"NAME\" = '" + district + " ISD'"

    lyr.definitionQuery = whereClause

    arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", whereClause)

    df.extent = lyr.getSelectedExtent()

    arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")

    arcpy.mapping.ExportToBMP(mxd, path + "\DistrictPicture.bmp", df) #single file

 

    #Generate report

    print("Generating report for: " + district + " ISD")

    arcpy.mapping.ExportReport(report_source=lyr,report_layout_file=path + r"\CrimeLayout.rlf",output_file=path + r"\temp" + str(pageCount) + ".pdf", starting_page_number=pageCount)

 

    #Append pages into final output

    print("Appending page: " + str(pageCount))

    pdfDoc.appendPages(path + r"\temp" + str(pageCount) + ".pdf")

    os.remove(path + r"\temp" + str(pageCount) + ".pdf")

    pageCount = pageCount + 1

 

pdfDoc.saveAndClose()

del mxd

 

22.创建地图手册

import arcpy

import os

 

# Create an output directory variable

outDir = r"C:\ArcpyBook\Ch4"  

 

# Create a new, empty pdf document in the specified output directory

finalpdf_filename = outDir + r"\MapBook.pdf"

if os.path.exists(finalpdf_filename):

  os.remove(finalpdf_filename)

finalPdf = arcpy.mapping.PDFDocumentCreate(finalpdf_filename)

 

# Add the title page to the pdf

print("Adding the title page  \n")

finalPdf.appendPages(outDir + r"\TitlePage.pdf")

 

# Add the index map to the pdf

print "Adding the index page  \n"

finalPdf.appendPages(outDir + r"\MapIndex.pdf")

 

# Export the Data Driven Pages to a temporary pdf and then add it to the

# final pdf. Alternately, if your Data Driven Pages have already been

# exported, simply append that document to the final pdf.

mxdPath = outDir + r"\Topographic.mxd"

mxd = arcpy.mapping.MapDocument(mxdPath)

print("Creating the data driven pages \n")

ddp = mxd.dataDrivenPages

temp_filename = outDir + r"\tempDDP.pdf"

 

if os.path.exists(temp_filename):

  os.remove(temp_filename)

ddp.exportToPDF(temp_filename, "ALL")

print("Appending the map series  \n")

finalPdf.appendPages(temp_filename)

 

# Update the properties of the final pdf

finalPdf.updateDocProperties(pdf_open_view="USE_THUMBS",

                             pdf_layout="SINGLE_PAGE")

 

# Save your result

finalPdf.saveAndClose()

 

# remove the temporary data driven pages file

if os.path.exists(temp_filename):

    print("Removing the temporary map series file")

    os.remove(temp_filename)

 

# Delete variables

#del finalPdf, mxd, ddp

 

23.查询发布服务的问题

import arcpy.mapping as mapping

wrkspc = r'c:\ArcpyBook\ch4'

mxd = mapping.MapDocument(wrkspc + r"\Crime.mxd")

 

service = 'Crime'

sddraft = wrkspc + service + '.sddraft'

mapping.CreateMapSDDraft(mxd, sddraft, service)

analysis = mapping.AnalyzeForSD(wrkspc + "Crime.sddraft")

 

for key in ('messages', 'warnings', 'errors'):

    print("----" + key.upper() + "----")

    vars = analysis[key]

    for ((message, code), layerlist) in vars.iteritems():

        print "    ", message, " (CODE %i)" % code

        print("     applies to:")

        for layer in layerlist:

            print(layer.name)

24.创建发布

import arcpy.mapping as mapping

wrkspc = r'c:\ArcpyBook\ch4'

mxd = mapping.MapDocument(wrkspc + r"\Crime.mxd")

 

service = 'Crime'

sddraft = wrkspc + service + '.sddraft'

mapping.CreateMapSDDraft(mxd, sddraft, service)

analysis = mapping.AnalyzeForSD(wrkspc + "Crime.sddraft")

 

if analysis['errors'] == {}:

    #execute StageService

    arcpy.StageService_server(sddraft,sd)

    #execute UploadServiceDefinition

    #arcpy.UploadServiceDefinition_server(sd, con)

else:

    #if the sddraft analysis contained errors, display them

    print(analysis['errors'])

 

25.调用裁剪工具

import arcpy

in_features = "c:/ArcpyBook/data/CityOfSanAntonio.gdb/Burglary"

clip_features = "c:/ArcpyBook/Ch5/EdgewoodSD.shp"

out_feature_class = "c:/ArcpyBook/Ch5/ClpBurglary.shp"

arcpy.Clip_analysis(in_features,clip_features,out_feature_class)

 

26.输出缓冲图层和按距离选择要素输出

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/TravisCounty"

try:

    # Buffer areas of impact around major roads

    streams = "Streams.shp"

    streamsBuffer = "StreamsBuffer"

    distance = "2640 Feet"

    schools2mile = "Schools.shp"

    schoolsLyrFile = 'Schools2Mile_lyr'

 

    arcpy.Buffer_analysis(streams, streamsBuffer, distance,'FULL','ROUND','ALL')

 

    # Make a layer

    arcpy.MakeFeatureLayer_management(schools2mile, schoolsLyrFile)

    arcpy.SelectLayerByLocation_management(schoolsLyrFile, 'intersect', streamsBuffer)

except Exception as e:

print e.message

 

 

  1. 创建工具箱 脚本

#Script to Import data to a feature class within a geodatabase

import arcpy, os

try:

    outputFC = arcpy.GetParameterAsText(0)

    fClassTemplate = arcpy.GetParameterAsText(1)

    f = open(arcpy.GetParameterAsText(2),'r')

    arcpy.CreateFeatureclass_management(os.path.split(outputFC)[0], os.path.split(outputFC)[1],"point",fClassTemplate)   

    lstFires = f.readlines()

    with arcpy.da.InsertCursor(outputFC) as cur:

        cntr = 1

        for fire in lstFires:

            if 'Latitude' in fire:

                continue

            vals = fire.split(",")

            latitude = float(vals[0])

            longitude = float(vals[1])

            confid = int(vals[2])

            pnt = arcpy.Point(longitude, latitude)

            feat = cur.newRow()

            feat.shape = pnt

            feat.setValue("CONFIDENCEVALUE", confid)

            cur.insertRow(feat)

            arcpy.AddMessage("Record number" + str(cntr) + "written to feature class")

            cntr = cntr + 1

except:

    print arcpy.GetMessages()

finally:

    f.close()                     

   

28.创建的python格式工具箱

import arcpy

import requests

import json

 

class Toolbox(object):

    def __init__(self):

        """Define the toolbox (the name of the toolbox is the name of the

        .pyt file)."""

        self.label = "Toolbox"

        self.alias = ""

 

        # List of tool classes associated with this toolbox

        self.tools = [USGSDownload]

 

 

class USGSDownload(object):

    def __init__(self):

        """Define the tool (tool name is the name of the class)."""

        self.label = "USGS Download"

        self.description = "Download from USGS ArcGIS Server instance"

        self.canRunInBackground = False

 

    def getParameterInfo(self):

 

        """Define parameter definitions"""

        # First parameter

        param0 = arcpy.Parameter(

            displayName="ArcGIS Server Wildfire URL",

            name="url",

            datatype="GPString",

            parameterType="Required",

            direction="Input")

        param0.value = "http://wildfire.cr.usgs.gov/arcgis/rest/services/geomac_dyn/MapServer/0/query"

 

        # Second parameter

        param1 = arcpy.Parameter(

            displayName="Output Feature Class",

            name="out_fc",

            datatype="DEFeatureClass",

            parameterType="Required",

            direction="Input")

 

        params = [param0, param1]

        return params

 

    def isLicensed(self):

        """Set whether tool is licensed to execute."""

        return True

 

    def updateParameters(self, parameters):

        """Modify the values and properties of parameters before internal

        validation is performed.  This method is called whenever a parameter

        has been changed."""

        return

 

    def updateMessages(self, parameters):

        """Modify the messages created by internal validation for each tool

        parameter.  This method is called after internal validation."""

        return

 

    def execute(self, parameters, messages):

        inFeatures = parameters[0].valueAsText

        outFeatureClass = parameters[1].valueAsText

 

        agisurl = inFeatures

 

        payload = { 'where': 'acres > 5','f': 'pjson', 'outFields': 'latitude,longitude,fire_name,acres'}

 

        r = requests.get(inFeatures, params=payload)

        decoded = json.loads(r.text)

 

        with arcpy.da.InsertCursor(outFeatureClass, ("SHAPE@XY", "NAME", "ACRES")) as cur:

            cntr = 1

            for rslt in decoded['features']:

                fireName = rslt['attributes']['fire_name']

                latitude = rslt['attributes']['latitude']

                longitude = rslt['attributes']['longitude']

                acres = rslt['attributes']['acres']

                cur.insertRow([(longitude,latitude),fireName, acres])

                arcpy.AddMessage("Record number: " + str(cntr) + " written to feature class")

                cntr = cntr + 1

                     

             

29.按属性选择并统计个数

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

    qry = '"SVCAREA" = \'North\''

    flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")

    arcpy.SelectLayerByAttribute_management(flayer, "NEW_SELECTION", qry)

    cnt = arcpy.GetCount_management(flayer)

    print "The number of selected records is: " + str(cnt)

except Exception as e:

    print e.message

   

30.位置选择和属性选择结婚

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

qry = '"DOW" = \'Mon\''

flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")

arcpy.SelectLayerByLocation_management (flayer, "COMPLETELY_WITHIN", "c:/ArcpyBook/Ch7/EdgewoodSD.shp")

arcpy.SelectLayerByAttribute_management(flayer, "SUBSET_SELECTION", qry)

cnt = arcpy.GetCount_management(flayer)

print("The total number of selected records is: " + str(cnt))

except Exception as e:

print(e.message)

 

31.创建图示表

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

    tView = arcpy.MakeTableView_management("Crime2009Table","Crime2009TView")

except Exception as e:

print e.message

 

32.按位置选择

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

    flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")

    arcpy.SelectLayerByLocation_management (flayer, "WITHIN_A_DISTANCE", "c:/ArcpyBook/Ch7/EdgewoodSD.shp","1 MILES")

    cnt = arcpy.GetCount_management(flayer)

    print("The number of selected records is: " + str(cnt))

except Exception as e:

    print(e.message)

 

 

 

 

 

 

33.创建游标检索要素中的要素

import arcpy.da

arcpy.env.workspace = "c:/ArcpyBook/Ch8"

with arcpy.da.SearchCursor("Schools.shp",("Facility","Name")) as cursor:

    for row in sorted(cursor):

        print("High school name: " + row[1])

34.按照条件检索

import arcpy.da

arcpy.env.workspace = "c:/ArcpyBook/Ch8"

with arcpy.da.SearchCursor("Schools.shp",("Facility","Name"), '"FACILITY" = \'HIGH SCHOOL\'') as cursor:

        for row in sorted(cursor):

                print("School name: " + row[1])

35.按需返还几何对象的相关几何值

import arcpy.da

import time

arcpy.env.workspace = "c:/ArcpyBook/Ch8"

start = time.clock()

with arcpy.da.SearchCursor("coa_parcels.shp",("PY_FULL_OW","SHAPE@")) as cursor:

    for row in cursor:

        print("Parcel owner: {0} has a location of: {1}".format(row[0], row[1]))

elapsed = (time.clock() - start)

print("Execution time: " + str(elapsed))

 

36.插入点元素

import arcpy

import os

 

arcpy.env.workspace = "C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb"

f = open("C:/ArcpyBook/Ch8/WildfireData/NorthAmericaWildfires_2007275.txt","r")

lstFires = f.readlines()

try:

        with arcpy.da.InsertCursor("FireIncidents",("SHAPE@XY","CONFIDENCEVALUE")) as cur:

                cntr = 1

                for fire in lstFires:

                        if 'Latitude' in fire:

                                continue

                        vals = fire.split(",")

                        latitude = float(vals[0])

                        longitude = float(vals[1])

                        confid = int(vals[2])

                        rowValue = [(latitude,longitude),confid]

                        cur.insertRow(rowValue)

                        print("Record number " + str(cntr) + " written to feature class")

                        cntr = cntr + 1

except Exception as e:

        print(e.message)

finally:

    f.close()

 

37.更新字段信息

import arcpy

 

arcpy.env.workspace = "C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb"

try:

#create a new field to hold the values

arcpy.AddField_management("FireIncidents","CONFID_RATING","TEXT","10")

print("CONFID_RATING field added to FireIncidents")

with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:

cntr = 1

for row in cursor:

# update the confid_rating field

if row[0] <= 40:

row[1] = 'POOR'

elif row[0] > 40 and row[0] <= 60:

row[1] = 'FAIR'

elif row[0] > 60 and row[0] <= 85:

row[1] = 'GOOD'

else:

row[1] = 'EXCELLENT'

cursor.updateRow(row)

print("Record number " + str(cntr) + " updated")

cntr = cntr + 1

except Exception as e:

print(e.message)

38.删除匹配的要素

import arcpy

import os

 

arcpy.env.workspace = "C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb"

try:

with arcpy.da.UpdateCursor("FireIncidents",("CONFID_RATING"),'[CONFID_RATING] = \'POOR\'') as cursor:

cntr = 1

for row in cursor:

cursor.deleteRow()

print("Record number " + str(cntr) + " deleted")

cntr = cntr + 1

except Exception as e:

    print(e.message)

39.编辑要素属性更新

import arcpy

import os

 

arcpy.env.workspace = "C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb"

try:

edit = arcpy.da.Editor('C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb')

edit.startEditing(True)

with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:

cntr = 1

for row in cursor:

# update the confid_rating field

if row[0] > 40 and row[0] <= 60:

row[1] = 'GOOD'

elif row[0] > 60 and row[0] <= 85:

row[1] = 'BETTER'

else:

row[1] = 'BEST'

cursor.updateRow(row)

print("Record number " + str(cntr) + " updated")

cntr = cntr + 1

edit.stopEditing(True)

except Exception as e:

print(e.message)

 

40.读取要素的几何信息

import arcpy

infc = "c:/ArcpyBook/data/CityOfSanAntonio.gdb/SchoolDistricts"

# Enter for loop for each feature

for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):

    # Print the current multipoint's ID

    print("Feature {0}:".format(row[0]))

    partnum = 0

 

    # Step through each part of the feature

    #

    for part in row[1]:

        # Print the part number

        #

        print("Part {0}:".format(partnum))

 

        # Step through each vertex in the feature

        #

        for pnt in part:

            if pnt:

                # Print x,y coordinates of current point

                #

                print("{0}, {1}".format(pnt.X, pnt.Y))

            else:

                # If pnt is None, this represents an interior ring

                #

                print("Interior Ring:")

        partnum += 1

 

41.遍历文件的名称

import arcpy.da as da

import os

 

print("os walk")

 

for dirpath, dirnames, filenames in os.walk(os.getcwd()):

    for filename in filenames:

        print(filename)

 

print("arcpy da walk")

 

for dirpath, dirnames, filenames in da.Walk(os.getcwd(),datatype="FeatureClass"):

    for filename in filenames:

        print(os.path.join(dirpath, filename))

 

42.获得列表0

import arcpy

arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"

fcList = arcpy.ListFeatureClasses()

for fc in fcList:

print(fc)

 

43.获得列表1

import arcpy

arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"

fcList = arcpy.ListFeatureClasses("C*")

for fc in fcList:

    print(fc)

44.获得列表2

import arcpy

arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"

fcList = arcpy.ListFeatureClasses("C*","polygon")

for fc in fcList:

    print(fc)

 

45.获取元素的字段列表

import arcpy

 

arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

    fieldList = arcpy.ListFields("Burglary")

    for fld in fieldList:

        print("%s is a type of %s with a length of %i" % (fld.name, fld.type, fld.length))

except Exception as e:

    print(e.message)

 

46.要素类的描述信息

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data"

try:

    descRaster = arcpy.Describe("AUSTIN_EAST_NW.sid")

    ext = descRaster.extent

    print("XMin: %f" % (ext.XMin))

    print("YMin: %f" % (ext.YMin))

    print("XMax: %f" % (ext.XMax))

    print("YMax: %f" % (ext.YMax))

 

    sr = descRaster.SpatialReference

    print(sr.name)

    print(sr.type)

except Exception as e:

    print e.message

 

47.获取要素的描述信息1

import arcpy

arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"

try:

    descFC = arcpy.Describe("Burglary")

    print("The shape type is: " + descFC.ShapeType)

    flds = descFC.fields

    for fld in flds:

        print("Field: " + fld.name)

        print("Type: " + fld.type)

        print("Length: " + str(fld.length))

    ext = descFC.extent

    print("XMin: %f" % (ext.XMin))

    print("YMin: %f" % (ext.YMin))

    print("XMax: %f" % (ext.XMax))

    print("YMax: %f" % (ext.YMax))

except:

    print(arcpy.GetMessages())

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

发布了12 篇原创文章 · 获赞 9 · 访问量 1732

猜你喜欢

转载自blog.csdn.net/qq_37141536/article/details/105378538