Get only first seven digits of a file

567
3
Jump to solution
04-22-2019 02:12 PM
JaredPilbeam2
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, re

ws = r'path\to\Projects\DOT_SignInventory'
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'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 operation
edit.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 operation
edit.stopOperation()
# Stop the edit session and save the changes
edit.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.

0 Kudos
1 Solution

Accepted Solutions
JoeBorgione
MVP Emeritus

Here's the concept:

var = '0110100_20180607'

var2 = var[:7]

'''var 2 = '0110100' '''‍‍‍‍‍
That should just about do it....

View solution in original post

3 Replies
JoeBorgione
MVP Emeritus

Here's the concept:

var = '0110100_20180607'

var2 = var[:7]

'''var 2 = '0110100' '''‍‍‍‍‍
That should just about do it....
JaredPilbeam2
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.

0 Kudos
DanPatterson_Retired
MVP Emeritus
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