Saturday, 11 February 2017

Using ArcPy to convert .txt to shapefile with coordinate system?


I tried to define my coordinate system on creating the shapefile but when I zoom to layer I don't see my features and ArcGIS crashes. I know it's not in the coordinate system I defined for it but it shows the coordinate under properties but doesn't reflect when I zoom to layer. Here is my python code:


import arcpy


newfcName ="newfc.shp"

outpath = r"C:/FLOOD/IKEJA AND KOSOFE"

# Declaration
arcpy.env.overwriteOutput=True

arcpy.env.workspace= outpath

# Create new Shapefile and add FIELDS

newfc = arcpy.CreateFeatureclass_management(outpath, newfcName, "Point")
# get the coordinate system by describing a feature class
dsc = arcpy.Describe("newfc.shp" )

coord_sys = dsc.spatialReference

try:
# run the tool
arcpy.DefineProjection_management(newfcName , coord_sys)


# print messages when the tool runs successfully
print(arcpy.GetMessages(0))

except arcpy.ExecuteError:
print(arcpy.GetMessages(2))

except Exception as ex:
print(ex.args[0])

arcpy.AddField_management(newfc, "X", "STRING", field_length = 50)

arcpy.AddField_management(newfc, "Y", "STRING", field_length = 50)
arcpy.AddField_management(newfc, "Z", "STRING", field_length = 50)
arcpy.AddField_management(newfc, "I", "FLOAT", field_length = 50)

# Reference Cursors
cursor=arcpy.da.InsertCursor(newfc, ["X", "Y", "Z", "I"])

# Read File
a = open("C:/FLOOD/IKEJA AND KOSOFE/DEM/532722.txt","r")


inputF = a.readlines()

for line in inputF:
xCoordinate, yCoordinate, zValue, iValue = line.split(" ")

newRow = (str(xCoordinate), str(yCoordinate), str(zValue), float(iValue))

cursor.insertRow(newRow)

a.close()


Answer



You need to populate the geometry column, for example with the SHAPE@XY token:


cursor=arcpy.da.InsertCursor(newfc, [ "SHAPE@XY", "X", "Y", "Z", "I"])

# Read File
a = open("C:/FLOOD/IKEJA AND KOSOFE/DEM/532722.txt","r")

inputF = a.readlines()

for line in inputF:

xCoordinate, yCoordinate, zValue, iValue = line.split(" ")

xy = (float(xCoordinate), float(yCoordinate))

newRow = (xy, str(xCoordinate), str(yCoordinate), str(zValue), float(iValue))

cursor.insertRow(newRow)

I don't understand how you're defining the coordinate system - it looks like you're getting the (empty) coordinate system from your newly created shapefile and then setting it to the same empty object, though maybe this a typo?


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...