Error 000728 when trying to read from CSV to XYEventLayer

2886
4
10-18-2016 06:14 AM
HanliePretorius
New Contributor III

Hi,

I'm trying to convert a CSV file to an XY layer using arcpy.MakeXYEventLayer_management but I'm getting an error:

ERROR 000728: Field Easting does not exist within table
ERROR 000728: Field Northing does not exist within table

I can't figure out why I'm getting this error. Can someone please help me?

These are the headings and the first three records of my CSV file (temp.csv), which is in the C:\temp folder:

Easting,Northing,Time,PingNo
93472.9,3657803.3,105530,47701
93453.0,3657772.8,105545,47760
93449.5,3657739.5,105600,47820

The code I'm using is:

import glob, os, csv, arcpy

inFolder = r'C:\temp'

# Set environment settings
arcpy.env.workspace = inFolder

def makePoints(inTable,lineName):
    try:
    # Set the local variables
        in_Table = inTable
        x_coords = 'Easting'
        y_coords = 'Northing'
        out_Layer = 'points_layer'
        saved_Layer = os.path.join(inFolder, 'points.lyr')

        # Set the spatial reference to UTM 34S
        spRef = arcpy.SpatialReference(32734)

        # Make the XY event layer...

        arcpy.MakeXYEventLayer_management(in_Table, x_coords, y_coords, out_Layer, spRef)

    except Exception as err:

        print(err.args[0])


def main():
    # create points layer from temporary csv file
    makePoints('temp.csv',lineName)


if __name__ == '__main__':
    main()

Thanks

Hanlie

Tags (2)
0 Kudos
4 Replies
BrittneyWhite1
Esri Contributor

Hi Hanlie,

If you look at the csv in ArcGIS Desktop software as a table, and check the field properties, are the Northing and Easting field types numbers?

From this tech article:

"If the XY fields do not show up in the Add XY Data tool, the XY fields are not numeric fields.

SOLUTION: Add two new fields for the XY values and set the field type to Double. Use the Field Calculator to populate the values.

REASON: The Add XY Data tool will only work with true numbers. "

0 Kudos
HanliePretorius
New Contributor III

Hi Brittney,

Thanks for the suggestion.

When I add the file as XY data in ArcMap and look at the field

properties, Easting and Northing are DOUBLE data types, so I don't

think that's the problem.

Regards

Hanlie

2016-10-18 15:36 GMT+02:00, Brittney White <geonet@esri.com>:

Brittney White

replied to the discussion

"Re: Error 000728 when trying to read from CSV to XYEventLayer"

To view the discussion, visit:

https://community.esri.com/message/641518-re-error-000728-when-trying-to-read-from-csv-to-xyeventlayer?commentID=641518&et=watches.email.thread#comment-641518

>

0 Kudos
DanPatterson_Retired
MVP Emeritus

add a print statement to print the actual table name prior to getting the field... sometimes the error has nothing to do with the actual line, but with the preceeding.  So if the inTable name isn't correct, perhaps it returns the field not found error first

0 Kudos
HanliePretorius
New Contributor III

I could not figure out what the problem was, so I used a completely different approach, bypassing the CSV file. I tried using a CSV file primarily because Make XY Event layer is apparently a very fast operation and the original file doesn't have a consistent spacing between its columns. However, Python is clever enough to seperate out the columns. Also, I only work with small amounts of data, so speed doesn't really matter.

In case anyone is interested, the code is below. It reads a text file as input of a very specific format, of which the first few rows are:

$  1,  19, 0, 4, 1
13062016 0
     93472.9    3657803.3  105530   47701 0000
     93453.0    3657772.8  105545   47760 0000
     93449.5    3657739.5  105600   47820 0000

The first two lines contain meta data and the columns are Easting, Northing, Time, Ping Number, Ignore.

#-------------------------------------------------------------------------------
# Name:        Txt2Line
# Purpose:     Converts survey points to lines - one line per text file
# Usage
# -----
# Assumptions:
# 1. Text files and shapefile are in the same folder.
# 2. Shapefile contains at least the following attributes:
#    LineNumber (text, 20)
#    LineDate (text, 😎
# 3. Shapefile is defined with the same spatial reference as the text files
# 4. Data points start on the third line of the text file and contains
#    the columns Easting, Northing, Time, PingNumber, Ignore seperated by spaces
# 5. Data points in text files are in time order.
#-------------------------------------------------------------------------------

import glob, os, csv , arcpy

# folder that contains the text files and the shapefile
inFolder = r'C:\temp'
# specifiy file type to search for
fileExt = 'nvx'
folderExt = os.path.join(inFolder, '*.' + fileExt)
# sepcify shapefile name - should be in the same folder as text files
polylineFC = os.path.join(inFolder, 'SurveyLines.shp')
# assume text files uses the same spatial reference as the shapefile
spatialRef = arcpy.Describe(polylineFC).spatialReference

# Set environment settings
arcpy.env.workspace = inFolder

def readFile(inFile):
    """
    Convert a space delimited file with two header lines to an arcpy array
    of points and convert the points to a line.
    Assumption: points in shapefile is in ping number order.
    """
    # get survey line name from file name - strip extension
    base = os.path.basename(inFile)
    lineNumber = os.path.splitext(base)[0]

    print 'Line number ', lineNumber

    #initialise a list to hold all the lines in the text file
    allLines = []

    # read lines in file into a list and remove line break charaters
    allLines= [line.rstrip('\n') for line in open(inFile, 'r')]

    # get survey line date (second line in file) and  first element in this line
    lineDate= allLines[1].split()[0]

    print 'Line date ', lineDate

    print 'This file contains ', len(allLines)-2, ' data points'

    # create an empty array object to hold points (vertices)
    vertexArray = arcpy.Array()

    # run through text file from the third line to the ned
    for pointNumber in range (2,len(allLines)):
        # print pointNumber, ':', allLines[pointNumber]
        # split line from file into elements of a list called dataItem using the spaces in between items
        dataItem = allLines[pointNumber].split()
##        # throw away 5th element (column) in list
##        dataItem = dataItem[:4]
##        print dataItem
        #dataItem = dataItem.append(lineName)
        #dataItem = dataItem.append(lineDate)
        # write row to temporary csv file
        #wr.writerow(dataItem)

        # get northing coordinate (second element in dataItem list)
        lat = dataItem[1]
        # print lat
        # get easting coordinate (first element in dataItem list)
        lon = dataItem[0]
        # print lon
        # print dataItem
        # create point feature from lat lon coordinates
        vertex = arcpy.Point(lon,lat)
        # print vertex
        # Make a point from the coordinate and add it to the array
        vertexArray.add(vertex)

    print 'Created ', len(vertexArray), ' points from file'
    # use vertex array to create line feature and insert into shapefile
    # with line number and line date as attributes
    try:
        with arcpy.da.InsertCursor(polylineFC, ("SHAPE@",'LineNumber','LineDate')) as cursor:
            polyline = arcpy.Polyline(vertexArray, spatialRef)
            cursor.insertRow((polyline,lineNumber,lineDate))
    except Exception as err:
        print(err.args[0])

def main():
    # search for file names that end in the specified extension
    fileCount = 0
    for fileName in glob.glob(folderExt):
        if fileName.endswith('.'+fileExt):
            print 'Found file ', fileName, ' processing it...'
            fileCount += 1
            # process files of the specified type in the function readFile
            readFile(fileName)
        else:
            print 'No files found'

    print 'Processed ', fileCount, ' files successfully'

if __name__ == '__main__':
    main()

0 Kudos