# Get only first seven digits of a file

131
3
04-22-2019 02:12 PM
MVP Regular Contributor

I have a working script that updates the 'photo' field with a file path to a JPG based on the 'post_number' field.

In other words, the script searches the directory for JPGs which it puts into a dictionary with it's file path. It then uses a cursor to update the photo field with a path to the JPG.

import arcpy, os, rews = r'path\to\Projects\DOT_SignInventory'jpgs = {} # empty dictionaryfor dirName, subdirList, fileList in os.walk(ws):    for fname in fileList:        jpgs[fname[:-4]] = os.path.join(dirName,fname)fc = r'path\to\Projects\DOT_SignInventory\Data.gdb\WCDOT_Signs'editws = os.path.dirname(fc)fields = ['OID@', 'Post_Number', 'Photo']# Start an edit session. Must provide the workspace.edit = arcpy.da.Editor(editws)# Edit session is started without an undo/redo stack for versioned data#  (for second argument, use False for unversioned data)edit.startEditing(False, True)# Start an edit operationedit.startOperation()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# Stop the edit operationedit.stopOperation()# Stop the edit session and save the changesedit.stopEditing(True)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

It works fine now because the 'Post_Number' field is the same as the JPG:

My problem is that the JPG will soon have a date concatenated to look like this, for example: 0110100_20180607. So, my question is how can I change the code so it uses only those first seven digits to populate the Photo field? They are both text fields.

Tags (3)
1 Solution

Accepted Solutions
MVP Esteemed Contributor

Here's the concept:

var = '0110100_20180607'var2 = var[:7]'''var 2 = '0110100' '''‍‍‍‍‍‍‍‍‍‍
can't wait to retire....
3 Replies
MVP Esteemed Contributor

Here's the concept:

var = '0110100_20180607'var2 = var[:7]'''var 2 = '0110100' '''‍‍‍‍‍‍‍‍‍‍
can't wait to retire....
MVP Regular Contributor

Thanks, that's it.

Here's how I put it in:

for dirName, subdirList, fileList in os.walk(ws):    for fname in fileList:        var = fname[:7]        jpgs[var[:-4]] = os.path.join(dirName,var)‍‍‍‍

The script runs without error, but now I have to figure out why the Photo field isn't being populated.

MVP Esteemed Contributor
var.split("_")[0]'0110100'‍‍‍

if the underscore is always the splitter and you need the first, and you might have to change 7 to 8 or something