需要将多个txt坐标点文件转为shp文件,其中,一个txt转为一个shp,txt名称为shp名称,不需要属性信息。
一、自定义txt格式:
txt格式:
J1,111,30
J2,112,30
J3,112.5,29
J1,111,30
二、txt转shp代码:
import arcpy
import os
import time
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
infd= arcpy.GetParameterAsText(0)
outfd= arcpy.GetParameterAsText(1)
arcpy.AddMessage('开始:'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
def txt2shp(txtPath,shpPath,shpName):
spatRef = arcpy.SpatialReference(4526)
fcls = arcpy.CreateFeatureclass_management(shpPath, shpName, "POLYGON", "", "", "", spatRef)
arcpy.AddField_management(shpPath + "\\" + shpName, "DKH", "TEXT", "", "",50)
iflds = ["MC", "SHAPE@XY"]
iCur = arcpy.InsertCursor(fcls)
lineNum = 1
dkh=0
for line in open(txtPath, 'r').readlines():
lineStrip = line.strip()
splitLine=line.split(",")
if splitLine[0]=="J1" and lineNum == 1:
row = iCur.newRow()#新建第一个要素
ary = arcpy.Array()
pt = arcpy.Point()
pt.X=splitLine[2]
pt.Y=splitLine[1]
ary.append(pt)
elif splitLine[0]=="J1ttttt" and lineNum != 1:
row.shape = ary
dkh=dkh+1
row.setValue("DKH", str(dkh))
iCur.insertRow(row)
row = iCur.newRow()#新建第N个要素
ary = arcpy.Array()
pt = arcpy.Point()
pt.X=splitLine[2]
pt.Y=splitLine[1]
ary.append(pt)
else:
pt = arcpy.Point()
pt.X=splitLine[2]
pt.Y=splitLine[1]
ary.append(pt)
lineNum=lineNum+1
row.shape = ary
dkh=dkh+1
row.setValue("DKH", str(dkh))
iCur.insertRow(row)
def eachFile(inFolder):
folderNames = os.listdir(inFolder)
for file in folderNames:
if(file[-4:]==".txt"):
txtPath = inFolder + '\\' + file
shpPath=outfd
shpName=file[0:-4]+".shp"
shpName.replace("-","x")
#print(txtPath)
arcpy.AddMessage(shpPath+ '\\' +shpName)
txt2shp(txtPath,shpPath,shpName)
eachFile(infd)
arcpy.AddMessage('结束:'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
三、初版代码,可以运行,但还缺少异常处理部分,缺少toolbox中的文件输入路径配置,记录参考。