Select to view content in your preferred language

Renaming a shapefile using values from a text field

3793
6
02-20-2013 01:19 PM
PeterDalrymple
Regular Contributor
Does anyone know how I might create a python script that would use an attribute value from a table and use that value as a file name prefix when renaming a shapefile?

For example, as part of my script I have converted a time field such that it contains no back slashes and can be used as a unique file name. Now that I have a field with the unique text I would like to rename a generic shapefile using the date text as a prefix inorder to make the file name unique.

For further clarification, the input file is always "generic.shp" and the desired output would look something like this, "02202013_generic.shp" based upon what date is used in the date field.

Any help would be appreciated.

Thanks!

Pete
Tags (2)
0 Kudos
6 Replies
NathanHeick
Frequent Contributor
Without having worked through the problem myself, I would say you will probably want to use a search cursor on whatever table has the date field or string field with the date in it.  That should give you access to the field values for a particular record in a table or feature class.  The new data access module might have something even more interesting, but I haven't gotten to even browsing it yet.  You could also do the date conversion in Python itself and just read the date directly from the date field.  I don't know what kind of result a search cursor gives for a date field in terms of Python types, but there are date, time, and datetime modules for working with dates and times.  That could help you avoid adding any unnecessary fields.  Lastly, I would say use arcpy.management.Rename() to rename generic.shp to 02202013_generic.shp.
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Hi Peter,

You should not name a shapefile beginning with a number:

http://support.esri.com/en/knowledgebase/techarticles/detail/23087

As the previous post stated, you could do this using a search cursor.  Not sure how you want to iterate through the table, but you could do this using a where clause.  Ex:

rows = arcpy.SearchCursor(fc, "OBJECTID = 1")
for row in rows:
    time = row.Time

del row, rows

arcpy.Rename_management(fc, time)
0 Kudos
PeterDalrymple
Regular Contributor
Thanks very much for your replies. The rename.management did work and so did search cursor recommendations. With some small changes I put the date string after the file name (e.g. generic_130220.shp).

Now for the next question...

When I rename the file, the name does not change in the TOC even after refreshing. I added a line of code to remove the feature from the mxd, but now would like to add the renamed file to the map. I have no problem adding a shapefile to the map at the beginning of the script when the shapefile is the same from day to day. However, once the shapefile has been renamed I am having a hard time finding a way to add the file based on its directory location instead of specific name. I can list the files in the directory, but can anyone point me in the right direction for then adding the listed files to my TOC? The plan is to then move the files to a directory where they will eventually be merged. If you have any recommendations on that process too I would greatly appreciate it since the files to be moved will vary from day to day as well.

Thanks again!

- Pete
0 Kudos
JakeSkinner
Esri Esteemed Contributor
To add the shapefile to ArcMap, you will first need to a make a feature layer, then add the feature layer.  Ex:

shapefile = r"C:\temp\Airports.shp"

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
arcpy.MakeFeatureLayer_management(shapefile, "Airports")
arcpy.mapping.AddLayer(df, shapefile, "AUTO_ARRANGE")


To move shapefiles to another directory, you can use the Copy geoprocessing tool.
0 Kudos
PeterDalrymple
Regular Contributor
Thanks Jake,

The code you posted specifies a specific path to the shapefile to be added. However, if the name of the file changes, the script would not be able to be used repeatedly without updating the file name/path. Is there a way to add/convert the layer based only on the directory in which it resides? That way the process could be automated to convert and add which ever file exists in the directory at the time the script was run. Once the file is copied to a new directory, the process could be run on any new files that are moved into the directory that is referenced by the script.

To further explain, I am creating a daily rountine to reformat shapefiles that are updated on a daily basis. The shapefiles are archived with a date in order to give them a unique name. However, the input file name is always the same until the date suffix is added. Once the suffix is added, the file name becomes unique, but the directory is always consistant. There will only ever be one file at a time in the directory where the processing is done. I am fairly new to python scripting so I apologize if I am not explaining this in the best way. For context, I've pasted the script below. Again, my apologies if the script seems a bit amateurish, but I am just geting started with the language:-)

As you can see, the last step is to remove the layer with the generic name. I am getting hung up on performing any further processes once the file name becomes variable. Ideally, I could reference the file based on its directory rather than its file name since the file name will be variable at this point.

mxd = arcpy.mapping.MapDocument("Current")
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]
newlayer = arcpy.mapping.Layer("C:\pathname\detentio.shp")
arcpy.mapping.AddLayer(df, newlayer,"TOP")
arcpy.AddField_management ("detentio", "Date_Txt", "TEXT","","",10,"Date_Txt","NULLABLE","NON_REQUIRED","")
arcpy.CalculateField_management("detentio","Date_Txt","[Date_Visit]","VB","#")
arcpy.ConvertTimeField_management("detentio","Date_Txt","MM/dd/yyyy;1033;;","Date_Mod","TEXT","yyMMdd;1033;;")
arcpy.DeleteField_management("detentio","Date_Txt")
arcpy.AddField_management ("detentio", "PhotoName", "TEXT","","",40,"PhotoName","NULLABLE","NON_REQUIRED","")
arcpy.CalculateField_management ("detentio", "PhotoName","[Date_Mod]& Chr(95) & right([photo],10)","VB")
arcpy.AddField_management ("detentio", "PhotoPath", "TEXT","","",200,"PhotoPath","NULLABLE","NON_REQUIRED","")
arcpy.CalculateField_management ("detentio", "PhotoPath",'"V:\newpathname\\"&[PhotoName]',"VB")
arcpy.DeleteField_management("detentio",["PhotoName"])
arcpy.DeleteField_management("detentio",["photo"])
from arcpy import env
env.workspace = "C:\pathname"
fc = "detentio"
rows = arcpy.SearchCursor("detentio", "FID = 1")
for row in rows:
     time = row.Date_Mod
     del row, rows
arcpy.DeleteField_management("detentio",["Date_Mod"])
arcpy.Rename_management("detentio.shp", "detentio" + "_" + time, "ShapeFile")
mxd = arcpy.mapping.MapDocument("Current")
for df in arcpy.mapping.ListDataFrames(mxd):
     for lyr in arcpy.mapping.ListLayers(mxd, "", df):
         if lyr.name.lower() == "detentio":
             arcpy.mapping.RemoveLayer(df, lyr)
print "Processing Complete."


Thanks again for your help!

- Pete
0 Kudos
JakeSkinner
Esri Esteemed Contributor
You can iterate through the directory using the arcpy.ListFeatureClasses function, and then add the shapefile that's found.  Ex:

import arcpy
from arcpy import env
env.workspace = r"C:\temp\python"

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

lstFCs = arcpy.ListFeatureClasses("*.shp")
for fc in lstFCs:
    arcpy.MakeFeatureLayer_management(fc, "fc")
    addLayer = arcpy.mapping.Layer("fc")
    lyr = arcpy.mapping.Layer("fc")
    lyr.name = fc.split(".")[0]
    arcpy.RefreshTOC()


This code finds all shapefiles within the C:\temp\python directory and adds it to ArcMap.
0 Kudos