Python与GIS之arcpy基础代码详解(一)

最近在学习arcpy,参考书籍为《面向ArcGIS的Python脚本编程》,把书中的重点Python脚本代码整理了一下,仅供参考。

第一部分为访问空间数据,脚本代码包括检查某个数据集是否存在,使用Describe函数描述数据集的属性,使用列表函数处理不同类型的元素,包括工作空间、字段、数据集、要素类、文件、栅格、属性表等。

访问空间数据

1.检查文件是否存在

语法:arcpy.Exists(<dataset>)

import arcpy
arcpy.env.workspace = r"E:\gis class\arcpy_1"
fc = "point.shp"
arcpy.Exists(fc)     # 返回结果为true or false

2.使用Describe函数描述数据

语法:<variable> = arcpy.Describe(<input dataset>)

arcpy.env.workspace = r"E:\gis class\arcpy_1"
fc = "point.shp"
desc = arcpy.Describe(fc)       # 获取包含数据集属性的描述对象
print desc.shapeType        # 获取该要素类的形状类型
print desc.path         #获取存储路径
sr = desc.spatialReference      #获取空间参考
print sr.name

输出结果

Point
E:\gis class\arcpy_1
Unknown

3.返回数据(列表函数)

3.1 ListFeatureClasses函数返回当前工作空间中的要素类列表

语法:ListFeatureClasses ( { wild_card },  { feature_type }, { feature_dataset } )    {  }为可选参数

例:ListFeatureClasses ( {“w*”,  “point” )   ——返回文件名以w开头,并且要素类型是点的所有要素类

import arcpy
arcpy.env.workspace = r"E:\gis class\arcpy_1"
fclist = arcpy.ListFeatureClasses()     # 返回包含要素类的列表
print fclist

输出结果

[u'line.shp', u'point.shp']

3.2 ListRasters函数返回当前工作空间中的矢量数据集列表

语法:ListRasters ( { wild_card },  { raster_type } )     与ListFeatureClasses函数相似

import arcpy
arcpy.env.workspace = r"E:\gis class\arcpy_1"
rslist = arcpy.ListRaster("","tif")     #返回该工作空间中数据类型为TIFF影像的栅格数据集列表
print rslist

3.3 ListFields函数返回某个要素类属性表的字段对象列表

语法:ListFields( dataset , { wild_card }, { field_type} )

ListFields函数返回的是字段列表对象,读取列表属性要使用for循环

import arcpy
arcpy.env.workspace = r"E:\gis class\data0408"
fc = "现状道路.shp"
fieldlist = arcpy.ListFields(fc)   # 返回字段列表对象,包括(字段名、别名、类型和长度)
for field in fieldlist:    # ListFields函数返回的是对象,所以要使用for循环读取对象的各个属性
    print "field name :{0} " " field length : {1} " " filed type : {2}".format(field.name,str(field.length),field.type

输出结果

field name :FID  field length : 4  filed type : OID
field name :Shape  field length : 0  filed type : Geometry
field name :Layer  field length : 254  filed type : String
field name :a  field length : 4  filed type : SmallInteger

3.4 操作列表

因为上述函数返回的都是字符串列表或者对象列表,所以对于返回列表,可以用Python为列表而设计的函数去处理,比如len()函数可以确定返回要素类数量,sort()函数可以将返回列表要素按字母顺序排列,关于列表函数这里就不过多叙述了

import arcpy
arcpy.env.workspace = r"E:\gis class\data0408"
fcs = arcpy.ListFeatureClasses()
print len(fcs)   # len()函数返回要素类数量
fcs.sort()      # sort()函数对返回要素类列表按字母重新排序
print fcs

 

转载自:https://blog.csdn.net/weixin_42164004/article/details/86714082

You may also like...