Use txt file as Fields in attribute table

3030
12
Jump to solution
02-05-2017 11:59 AM
AleahWorthem
New Contributor III

I am attempting to write a script so that instead of hardcoding the name of the new field as "CONFIVALUE" for the confidence value, I want to use the name of the third column in the header of the input text file.


For example, let's say that the first line of the input text file looks like this:

Latitude,Longitude,Confidence

In this case the field name should be "Confidence".

If the first line looked like this:

Latitude,Longitude,ConfidValue

Then the field name should be "ConfidValue".

The error if i have conField indexed as conField[2]:

Traceback (most recent call last):
File "C:\Users\Aleah\Desktop\PythonScripts\Lab7_Q5.py", line 22, in <module>
IndexError: list index out of range


The error i am receiving if i remove the index is:

Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 27, in <module>
File "C:\Program Files (x86)\ArcGIS\Desktop10.3\arcpy\arcpy\management.py", line 3246, in AddField
raise e
RuntimeError: Object: Error in executing tool

    import arcpy

    work = "C:\Scripts\Lab 7 Data\WildlandFires.mdb"
     arcpy.env.workspace = work # Set the workspace to the geodatabase
     arcpy.env.overwriteOutput = True

     iFile = "C:\Scripts\Lab 7 Data\NorthAmericaWildfires_2007275.txt"

     output = "NewFires.shp"
     threshold = 99

     f = open(iFile, 'r')# input text file C:\Scripts\Lab 7 Data\NorthAmericaWildfires_2007275.txt in "read" mode

     lstFires = f.readlines() # Read the lines of fire
     conField = []

     for line in f:
         comma = line.split(',')
         conField = comma
         print conField[2]

     field = ["SHAPE@", conField[2]] # represents the field names for each row in the feature class
     # Process: Create Feature Class

     arcpy.CreateFeatureclass_management(work, output, "POINT")

     arcpy.AddField_management(output, conField[2], "FLOAT")

     cursor_new = arcpy.da.InsertCursor(output, field)# add the new points that you will create to the "NewFires" feature class


     f.close() # close the file
     del cursor_new # release the cursor lock on the feature class

0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Emeritus

con_val = lstFires[0].strip().split(',')[-1]

View solution in original post

12 Replies
DanPatterson_Retired
MVP Emeritus

Aleah, perhaps you can format your code Code Formatting the Basics++

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Since "line 22" is generating the error, what exactly is line 22?

Also, does print conField[2] print the result you expect?

0 Kudos
DanPatterson_Retired
MVP Emeritus
comma = line.split(',')
conField = comma
print conField[2]

It appears to be a circular way around to splitting the line reference by the ',' then slicing it to get the last entry, it would be just as well be done as

conField= line.split(',')[2]
0 Kudos
AleahWorthem
New Contributor III

conField = []
for line in f:
     conField = line.split(',')[2]

field = ["SHAPE@", conField] # represents the field names for each row in the feature class
# Process: Create Feature Class

arcpy.CreateFeatureclass_management(work, output, "POINT")

arcpy.AddField_management(output, conField, "FLOAT")

Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 25, in <module>
File "C:\Program Files (x86)\ArcGIS\Desktop10.3\arcpy\arcpy\management.py", line 3246, in AddField
raise e
RuntimeError: Object: Error in executing tool

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

As Dan suggested, please use code formatting,  It makes it easier for people to read and for specific comments about the code.

Your first line, cornfield = [], is unnecessary because str.split() returns a list.

You are using file.readlines(), emphasis on plural, that reads "until EOF."  In your loop:

for line in f:
     conField = line.split(',')[2]

You are looping through the entire file contents, and by the time the loop finishes, conField contains the last line, not the first.

If you put a print statement after the loop is complete, what values are stored in conField?

0 Kudos
AleahWorthem
New Contributor III

conField = []
for line in f:
     conField = line.split(',')[2]

field = ["SHAPE@", conField] # represents the field names for each row in the feature class
# Process: Create Feature Class

arcpy.CreateFeatureclass_management(work, output, "POINT")

arcpy.AddField_management(output, conField, "FLOAT")

 

Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 25, in <module>
File "C:\Program Files (x86)\ArcGIS\Desktop10.3\arcpy\arcpy\management.py", line 3246, in AddField
raise e
RuntimeError: Object: Error in executing tool

0 Kudos
DarrenWiens2
MVP Honored Contributor

I assume that since you read all lines into the list, setting conField[2] to the third value in each line will ultimately result in the final value of your file, not the field name from the first line. You can access the first line of the file with f.readline() (reads only one line) or f.readlines()[0].

Also, you may be running into a problem if Python is reading a new line character at the end of your line. Try printing the split list to see the new line character:

>>> f = open(r'C:\junk\log.txt', 'r')
... my_list = f.readlines()
... print my_list[0]
... print my_list[0].split(',')
... 
field1,field2,field3

['field1', 'field2', 'field3\n']
0 Kudos
AleahWorthem
New Contributor III

f = open(iFile, 'r')# input text file C:\Scripts\Lab 7 Data\NorthAmericaWildfires_2007275.txt in "read" mode

lstFires = f.readlines() # Read the first lines of file

print (lstFires[0])
print (lstFires[0].strip().split(','))
This gives me :

Latitude,Longitude,Confidence

['Latitude', 'Longitude', 'Confidence']

But how can I access the Confidence string only, to be used later in arcpy.AddField_management

0 Kudos
DanPatterson_Retired
MVP Emeritus

con_val = lstFires[0].strip().split(',')[-1]