'''----------------------------------------------------------------------------------
Tool Name: CreateFeaturesFromTextFile
Source Name: CreateFeaturesFromTextFile.py
Version: ArcGIS 9.1
Author: Environmental Systems Research Institute Inc.
Required Argumuments: An Input Text File containing feature coordinates
An Input Character designating the decimal separator used in the text file.
An output feature class
Optional Arguments: A spatial reference can be specified. This will be the
spatial reference of the output fc.
Description: Reads a text file with feature coordinates and creates a feature class
from the coordinates.
----------------------------------------------------------------------------------''' import string, os, sys, locale, arcgisscripting
gp = arcgisscripting.create()
gp.overwriteoutput = 1 msgErrorTooFewParams = "Not enough parameters provided."
msgUnknownDataType = " is not a valid datatype. Datatype must be point, multipoint, polyline or polygon."
msgErrorCreatingPoint = "Error creating point %s on feature %s" # sets all the point properties
def createPoint(point, geometry):
try:
point.id = geometry[0]
point.x = geometry[1]
point.y = geometry[2]
# When empty values are written out from pyWriteGeomToTextFile, they come as 1.#QNAN
# Additionally, the user need not supply these values, so if they aren't in the list don't add them
if len(geometry) > 3:
if geometry[3].lower().find("nan") == -1: point.z = geometry[3]
if len(geometry) > 4:
if geometry[4].lower().find("nan") == -1: point.m = geometry[4]
return point
except:
raise Exception, msgErrorCreatingPoint try:
# get the provided parameters
inputTxtFile = open(gp.getparameterastext(0))
fileSepChar = gp.getparameterastext(1)
outputFC = gp.getparameterastext(2) # spatial reference is optional
outputSR = gp.getparameterastext(3) # make sure the text type specified in the text file is valid.
inDataType = inputTxtFile.readline().strip().lower()
dataTypes = ["point", "multipoint", "polyline", "polygon"]
if inDataType.lower() not in dataTypes:
msgUnknownDataType = "%s%s" % (inDataType, msgUnknownDataType)
raise Exception, msgUnknownDataType # create the new featureclass
gp.toolbox = "management"
gp.CreateFeatureclass(os.path.split(outputFC)[0], os.path.split(outputFC)[1], inDataType, "#", "ENABLED", "ENABLED", outputSR)
# create a new field to assure the id of each feature is preserved.
idfield = "File_ID"
gp.addfield(outputFC, idfield, "LONG")
# get some information about the new featureclass for later use.
outDesc = gp.describe(outputFC)
shapefield = outDesc.ShapeFieldName
# create the cursor and objects necessary for the geometry creation
rows = gp.insertcursor(outputFC)
pnt = gp.createobject("point")
pntarray = gp.createobject("Array")
partarray = gp.createobject("Array") locale.setlocale(locale.LC_ALL, '')
sepchar = locale.localeconv()['decimal_point'] # loop through the text file.
featid = 0
lineno = 1
for line in inputTxtFile.readlines():
lineno += 1
# create an array from each line in the input text file
values = line.replace("\n", "").replace("\r", "").replace(fileSepChar, sepchar).split(" ") # for a point feature class simply populate a point object and insert it.
if inDataType == "point" and values[0].lower() != "end":
row = rows.newrow()
pnt = createPoint(pnt, values)
row.SetValue(shapefield, pnt)
row.SetValue(idfield, int(values[0]))
rows.insertrow(row) # for a multipoint the text file is organized a bit differently. Groups of points must be inserted at the same time.
elif inDataType == "multipoint":
if len(values) > 2:
pnt = createPoint(pnt, values)
pntarray.add(pnt)
elif (len(values) == 2 and lineno != 2) or values[0].lower() == "end":
row = rows.newrow()
row.SetValue(shapefield, pntarray)
# store the feature id just in case there is an error. helps track down the offending line in the input text file.
if values[0].lower() != "end":
row.SetValue(idfield, featid)
featid = int(values[0])
else:
row.SetValue(idfield, featid)
rows.insertrow(row)
pntarray.removeall()
elif (len(values) == 2 and lineno == 2):
featid = int(values[0]) # for polygons and lines. polygons have a bit of logic for interior rings (donuts).
# lines use the same logic as polygons (except for the interior rings)
elif inDataType == "polygon" or inDataType == "polyline":
#takes care of
#adds the point array to the part array and then part array to the feature
if (len(values) == 2 and float(values[1]) == 0 and lineno != 2) or values[0].lower() == "end":
partarray.add(pntarray)
row = rows.newrow()
row.SetValue(shapefield, partarray)
# store the feature id just in case there is an error. helps track down the offending line in the input text file.
if values[0].lower() != "end":
row.SetValue(idfield, featid)
featid = int(values[0])
else:
row.SetValue(idfield, featid)
rows.insertrow(row)
partarray.removeall()
pntarray.removeall()
#adds parts and/or interior rings to the part array
elif (len(values) == 2 and float(values[1]) > 0) or values[0].lower() == "interiorring":
partarray.add(pntarray)
pntarray.removeall()
#add points to the point array
elif len(values) > 2:
pnt = createPoint(pnt, values)
pntarray.add(pnt)
elif (len(values) == 2 and lineno == 2):
featid = int(values[0]) inputTxtFile.close()
del rows
del row except Exception, ErrorDesc:
# handle the errors here. if the point creation fails, want to keep track of which point failed (easier to fix the
# text file if we do)
if ErrorDesc[0] == msgErrorCreatingPoint:
if inDataType.lower() == "point":
msgErrorCreatingPoint = msgErrorCreatingPoint % (values[0], values[0])
else:
msgErrorCreatingPoint = msgErrorCreatingPoint % (values[0], featid)
gp.AddError(msgErrorCreatingPoint)
elif ErrorDesc[0] != "":
gp.AddError(str(ErrorDesc)) gp.AddError(gp.getmessages(2)) # make sure to close up the fileinput no matter what.
if inputTxtFile: inputTxtFile.close()

create feature from text file的更多相关文章

  1. The 12th tip of DB Query Analyzer, powerful in text file process

    MA Gen feng ( Guangdong Unitoll Services incorporated, Guangzhou 510300) Abstract   It's very powerf ...

  2. [转]How to Import a Text File into SQL Server 2012

    Importing a using the OpenRowSet() Function The OPENROWSET bulk row set provider is accessed by call ...

  3. shell脚本执行时报"bad interpreter: Text file busy"的解决方法

    在执行一个shell脚本时,遇到了“-bash: ./killSession.sh: /bin/bash: bad interpreter: Text file busy”错误提示,如下所示: [or ...

  4. eclipse的使用-------Text File Encoding没有GBK选项的设置

    eclipse的使用-------Text File Encoding没有GBK选项的设置 2013-12-25 09:48:06 标签:java myeclipse使用 有一个项目是使用GBK编码的 ...

  5. Writing Text File From A Tabular Block In Oracle Forms

    The example given below for writing text file or CSV using Text_IO package from a tabular block in O ...

  6. 【转】shell脚本执行时报"bad interpreter: Text file busy"的解决方法

    1)问题现象: 在ubuntu下执行以下脚本( while_count),报错: -bash: ./while_count: /bin/bash: bad interpreter: Text file ...

  7. EXCEPTION:FATAL: UNABLE TO CREATE ‘…GIT/INDEX.LOCK’ FILE EXISTS

    FATAL: UNABLE TO CREATE ‘…GIT/INDEX.LOCK’ FILE EXISTS Hi, Today I will share you my other experience ...

  8. New text file line delimiter

    Window -> Preferences -> General -> Workspace : Text file encoding :Default : 选择此项将设定文件为系统默 ...

  9. ArcCatalog连接ArcSDE连接报:unable to create new database connection file,permission is denied

    参考博文:链接 ArcCatalog连接ArcSDE连接报:unable to create new database connection file,permission is denied 最近经 ...

随机推荐

  1. [iOS微博项目 - 3.3] - 封装网络请求

    github: https://github.com/hellovoidworld/HVWWeibo   A.封装网络请求 1.需求 为了避免代码冗余和对于AFN框架的多处使用导致耦合性太强,所以把网 ...

  2. oradmin相关用法

    [转]oradmin相关用法 创建例程: -NEW -SID sid | -SRVC 服务 [-INTPWD 口令] [-MAXUSERS 数量] [-STARTMODE a|m] [-PFILE 文 ...

  3. Mac配置JAVA_HOME

    首先打开终端,输入/usr/libexec/java_home,看到 /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home 说 ...

  4. PB学习笔记(一)

    前言:我绝对很痛恨PB.1.没人带2.自己摸索3.头发掉了4.老大不停的给任务5.这语言老的不行了6,代码可读性不是一般的差 我绝对很喜欢PB.1.自我学习成功后那种成就感2.老大也会帮给我看看,指点 ...

  5. oracle 学习笔记--用户管理

    oracle 用户管理 创建用户(需要具有dba权限的用户) create user 用户名 identified by 密码 defaule tablespace users     //默认表空间 ...

  6. WSO2 ESB

    什么是WSO2 ESB? WSO2 ESB是一个轻量级的易于使用的企业服务资源总线.WSO2 ESB允许系统管理员和SOA架构师,消息路由,虚拟化,中介,转换,日志记录,任务调度,负载平衡,失败了路由 ...

  7. 如何让DIV相对于body水平和垂直居中

    我们在设计页面的时候,经常要把DIV居中显示,而且是相对页面窗口水平和垂直方向居中显示,如让登录窗口居中显示.我们传统解决的办法是用纯CSS来让DIV居中.在本文中,我将给大家讲述如何用CSS和jQu ...

  8. until与till的用法归纳

    until与till的用法归纳 崔荣斌 until和till两者都可作介词.连词,一般情况下可以互换使用.用于肯定句时,主句的动词只用延续性的,它所表示的动作一直延续到till或until表示的时间为 ...

  9. C++学习笔记之由文本文件读取数据到vector模板建立的二维数组 并存储为新的文本文件

    阅读本文可首先参考: C++学习笔记之输入.输出和文件 测试数据: /*读取txt文件到二维数组*/ #include <iostream> #include <fstream> ...

  10. COM组件入门(一)

    近期须要用到COM组件的知识,看了看COM编程指南,感觉还不错.把我的学习心得记录下来.这是我依据教程写的demo StopWatch接口实现部分,接口部分我的项目是动态库,主要源代码例如以下: 完整 ...