Select to view content in your preferred language

Script to save attachments overwriting duplicates

502
4
10-28-2024 02:48 PM
SamBelisleLID1990
Emerging Contributor

I have a script I am running in ArcGIS Pro that downloads a file geodatabase of a feature class and saves attachments as JPEGs from the FGDB. The original feature class often has multiple attachments for each record, and sometimes multiple records for each 'site.' I need all of these attachments to save separately. 

My script currently overwrites the previous attachment with the latest one. I need it to save a new attachment with "--2" or "--3" at the end of each subsequent attachment. So a site with one recrod that has 2 attachments would have two JPEGs saved: "SiteNumber.jpg" and "SiteNumber--2.jpg".

0 Kudos
4 Replies
JakeSkinner
Esri Esteemed Contributor

Hi @SamBelisleLID1990, take a look at the Export Attachments tool, which is new at ArcGIS Pro version 3.3.  This tool provides options on how to handle the name format of the exported attachments:

JakeSkinner_0-1730206441629.png

 

0 Kudos
SamBelisleLID1990
Emerging Contributor

Thank you @JakeSkinner, I am able to name the files according to the field values. The problem is that I can't get it to recognize the duplicates. The first attachment will download with the correct file name, then the second attachment will overwrite the first attachment with the same file name, meaning the data is not captured instead of saving as a new file. 

0 Kudos
JakeSkinner
Esri Esteemed Contributor

If you specify Add Field Values as Suffix it will handle duplicates by adding an _1, _2, etc.  

JakeSkinner_2-1730240653065.png

 

 

JakeSkinner_1-1730240612848.png

 

GrantHerbert
Frequent Contributor

You can loop through and check the existence of a file in the output location, and update the name using an approach like the following (untested and not properly indented):

filenum = 2
attachment = item[0]
filename = f'{item[3]}.jpg'
while os.path.exists(os.path.join(fileLocation, filename)): #check the output location
arcpy.AddMessage(f'{filename} already exists, trying --{filenum}')
filename = f'{item[3]}--{filenum}.jpg'
filecount += 1
open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())