I've been tasked with updating attribute table fields with file paths to image files in a folder based on a unique ID. I'm having trouble thinking up a script that will do this? I'm working on a standalone script in ArcGIS Pro 2.3.1 Arcpy.
This is an example of how the table should look. Every JPG has a unique ID that matches the Post_Number field unique ID. Currently, the paths to the JPGs are entered manually into the table, and there are 1000s of them.
All I've done so far is create a cursor that searches the Post_Number and Photo fields.
import arcpy, os
fc = r'pathto\Projects\DOT_SignInventory\Data.gdb\WCDOT_Signs'
fields = ['Post_Number', 'Photo']
with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
print(u"{0}, {1}".format(row[0], row[1]))
Solved! Go to Solution.
Thumbs.db is a hidden Windows file/folder. Windows likes to index photos and create icons, so it will have a reference to your jpegs . So between lines 9 and 10 in my sample code above, a test would need to be added to make sure that Thumbs.db is being excluded. I haven't tested it, but perhaps this would work for line 9:
if file.endswith(".jpg") and 'Thumbs.db' not in root:
I couldn't get the os.walk portion of the code you provided to get to the jpgs. If I ran that portion of the script to test it (left out the cursor portion) it would iterate a folder in that same directory that had a jpg, but then stop there. It didn't find any other jpgs. So I changed those lines to this:
ws = r'C:\path\to\jpegs\root'
jpgs = {} # empty dictionary
for dirName, subdirList, fileList in os.walk(ws):
for fname in fileList:
jpgs[fname[:-4]] = os.path.join(dirName,fname)
Anyway, thanks to all of your help this does what I want:
import arcpy, os
ws = r'C:\path\to\jpegs\root'
jpgs = {} # empty dictionary
for dirName, subdirList, fileList in os.walk(ws):
for fname in fileList:
jpgs[fname[:-4]] = os.path.join(dirName,fname)
fc = r'pathto\Projects\DOT_SignInventory\Data.gdb\WCDOT_Signs'
fields = ['OID@', 'Post_Number', 'Photo']
with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
try:
row[2] = jpgs[row[1]]
cursor.updateRow(row)
except KeyError:
print("No photo for: {}".format(row[1]))
del cursor