Howto: 使用Python从一个字段中获取值并把它写入到文本文件中

文章编号 : 34574
软件: ArcGIS - ArcEditor 9.2, 9.3, 9.3.1 ArcGIS - ArcInfo 9.2, 9.3, 9.3.1 ArcGIS - ArcView 9.2, 9.3, 9.3.1
操作系统: N/A
已邀请:

易智瑞技术支持

赞同来自:

摘要: 示例描述了如何通过Select Layer By Attribute工具获取一个图层中的部分要素,再通过Select Layer By Location工具进一步获取与这些要素共享边界的多边形,并将选中要素的指定字段值写入到文本文件中。

为了在Python中完成此任务,需要使用SearchCursor方法来对指定字段中的值迭代。

内容: 以下是此过程的大体步骤,示例使用了邮政编码多边形Shapefile。
  1. 设定环境变量及需要的变量值。 # Import Modules... import arcgisscripting, os, sys, string # Create the Geoprocessor and set overwrites... gp = arcgisscripting.create() gp.OverwriteOutput = 1 # Set Variables... gp.Workspace = r"D:\627514" # this is the folder that contains the data input = "testdata.shp" # the zip code shapefile lyr = "test_layer" # the name of the Make Feature Layer output
  2. 将输入的shapefile变成Feature Layer,这样才可以对其使用Select Layer By Attribute和Select Layer By Location工具。 # Process: Make Feature Layer... gp.MakeFeatureLayer_management(input, lyr)
  3. 创建用于存放输出结果的文本文件。 # Create the Text File to write the zip values to... outFile = open(r"D:\627514\zipcode.txt", "w") 
  4. 新建第一个Search Cursor,它用来对Shapefile中的指定字段中的值进行循环。 # Build the Search Cursor... fcSearch = gp.SearchCursor(lyr, "", "", "ZIP") fc = fcSearch.Next()
  5. 创建循环结构对指定字段中的每个值进行循环,这个过程中使用了Select Layer By Attribute与Select Layer By Location工具。在Select Layer By Attribute中需要SQL表达式,因此需要创建SQL表达式。 while fc: exp = "ZIP" + "='" + str(fc.getvalue("ZIP"))+"'" # Process: Select by Attribute... gp.SelectLayerbyAttribute_management(lyr, "NEW_SELECTION", exp) # Process: Select by Location... gp.SelectLayerbyLocation_management(lyr, "BOUNDARY_TOUCHES", lyr, "", "NEW_SELECTION")
  6. 创建另外一个Search Cursor对上面的选择集进行循环,先将Select Layer By Attribute选择记录中指定字段的值写入文本文件,再将Select Layer By Location选中的记录中指定字段的值写入到文本文件。该层循环完全嵌套在上一层循环中。 # Build another Search Cursor to grab the zip values out of lyr... txtSearch = gp.SearchCursor(lyr, "", "", "ZIP") txtS = txtSearch.Next() outFile.write("Zip Code: " + str(fc.getvalue("ZIP"))+ "\n") while txtS: zval = str(txtS.getvalue("ZIP")) outFile.write(zval + "\n") txtS = txtSearch.Next() fc = fcSearch.Next()
  7. 循环层之外,关闭文本文件并释放内存中的所有变量。 outFile.close() # this closes the text file del gp, input, lyr, fcSearch, fc, exp, outFile, zval, txtS, txtSearch
  8. 文本文件中内容如下: Zip Code: 08003 08003 08034 08043 08053 08054 Zip Code: 08004 08004 08009 08053 08055 08088 08089






创建时间:2008-03-25
最近更新: 2011-05-03


原文链接
http://support.esrichina.com.c ... .html

要回复问题请先登录注册