I have a script for traversing a directory tree and finding shapefiles with a particular name. The issue I'm having is that the shapefiles are named improperly for databasing i.e. 20160527_Whatever.shp (total of 24 characters). The script is supposed to remove the date from the beginning, and add it to the end for the filename. Currently it outputs the same filename over and over again and fails. Snippet of the portion failing below (haven't done a lot of string parsing)

import arcpy, os, fnmatch
from arcpy import env


rootDir = "whatever directory"
search = "whatever criteria"
outGDB = "whatever GDB"

shpLst = []
for root, dirs., files in os.walk(rootDir, topdown=True):
    for filename in fnmatch.filter(files, search):
        shpLst.append(os.path.join(root, filename))

for fc in shpLst:
    outName= (os.path.basename(shpLst[0][-30:-4]) + "_" + os.path.basename(shpLst[0][9:-31]))
   arpy.FeatureClassToFeatureClass_management(fc, outGDB, outName, "", "", "")
   print outName + " sent to " + outGDB

As I said, the above outputs the same exact file name every time, so I'm guessing it's a problem with the way I'm parsing the string?

  • 1
    Your outname is the same every time. Remove [0]
    – FelixIP
    May 28, 2016 at 4:47
  • 1
    I would not use a List for the shapenames but load the data with the arcpy-functions for it like arcpy.ListFeatureClasses, ListDatasets, ListWorkspaces. Its mostly way easier. Or use arcpy.da.walk . But thats not a mistake, just a hint.
    – Matte
    May 28, 2016 at 4:48
  • Wow.. that easy... thanks Felix, feel a bit ridiculous now
    – geodranic
    May 28, 2016 at 4:50
  • Made difficult to rread. Much easier: get basename. Replace .shp by ''. Split using _. Concatenate [1] and [0]
    – FelixIP
    May 28, 2016 at 4:54

1 Answer 1


By using os.path.basename(shpLst[0]), you are specifying the first list item in the shpLst list. This will be the same every time. Instead, you need to perform string manipulation with the fc variable.

Slicing a basename can be problematic if the number of characters is different for any of the basenames. The os module's split method is what is needed in your case. Here is a simplified example:

import os

out_workspace = r'/path/to/out_workspace'

shpLst = [r'/path/to/20160527_Whatever.shp',

for fc in shpLst:
    parts = os.path.basename(fc).split(".")[0].split("_")
    outName = parts[1] + "_" + parts[0] + ".shp" 
    final = os.path.join(out_workspace, outName)
  • This is much more efficient code, and fixed the issue. Thanks! Now I just have to figure out why im getting a 999999 error
    – geodranic
    May 28, 2016 at 6:15
  • No shp if destination is fgdb
    – FelixIP
    May 28, 2016 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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