2

So far I have written the following and both work:

arcpy.AddField_management("Wards", "test", "SHORT")

iFile =r'\file\Book1.txt'
f = open(iFile, 'r')

What I want to do is populate the new field 'test' with a field (value) from the iFile based on a match on two codes in the seperate file.

The text file has:

Code, Value

I think it might need updateCursor with a where statement ... or an if?

if (code in iFile == code in Wards):
    raise iFile(value) 
0

1 Answer 1

5

You can create a dictionary from the textfile and use in the UpdateCursor:

Textfile:

A Monkey
B Fish
C Cat
D Dog

Feature class attribute table:

enter image description here

Code:

import arcpy
feature_class=r"C:\TEST.gdb\polygons123"

#Create a dictionary for use in the updateCursor:
d = {}
with open(r"C:\Test\textfile.txt") as f:
    for line in f:
        (key, val) = line.split()
        d[(key)] = val

arcpy.AddField_management(in_table=feature_class, field_name='Newfield', field_type='TEXT', field_length=20)
with arcpy.da.UpdateCursor(feature_class,['IDField','NewField']) as cursor:
    for row in cursor:
        try:
            row[1]=d[row[0]] #'NewField' = Dictionary['IDField']
            cursor.updateRow(row)
        except:
            pass

Result:

enter image description here

2
  • 1
    That has worked perfectly - thank-you very much for your help
    – tj123
    Commented Mar 28, 2017 at 12:53
  • 1
    Note that depending on the file format, it might be better to open it using the csv module.
    – jpmc26
    Commented Mar 28, 2017 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.