Tuesday, 29 May 2018

arcmap - Using ArcPy to Rename Feature Class by Field?


I made a little model and at the end I want to rename the feature class file to something based on the fields in that feature class. I want to rename that feature class by the date the data was collected (its a field in the FC) follow by an underscore then by the editor of the FC (which is also a field). The way our files are setup is the data is collected on the same date by one person. So there is no danger of having 2 editors to one file or 2 dates. I am just really new to Python.



I used it to do field calculations and have that understood fairly well. But I am trying to figure out the command to pull the field value and print it in the rename.


I have the stock python script for rename


# Name: Rename_Example2.py
# Description: Rename fileGDB feature class

# Import system modules
import arcpy
from arcpy import env

# Set workspace

env.workspace = "C:/workspace/test.gdb"

# Set local variables
in_data = "test"
out_data = "testFC"
data_type = "FeatureClass"

# Execute Rename
arcpy.Rename_management(in_data, out_data, data_type)




How do I put the fields with the data into the "out_data"? I figure I have to collect it some how, maybe in the local variables? You don't need to write the script for me, but if you could point me to a solid source for commands and strings that would be great. I already checked out other threads and the python site.


https://docs.python.org/2/library/string.html#formatspec


It seems close to what I need but I am still not getting it.



Answer



In case someone has the same issue, this is my solution.


import arcpy

fc = "C:\mygdb\myfile"
f1, f2, f3 = "EDITOR", "SPECIES", "OBJECTID"

clause = arcpy.AddFieldDelimiters(fc, f3) + "= 1"
for row in sorted (arcpy.da.SearchCursor (fc, [f1, f2], clause)):
print ("{0}_{1}".format(row[0], row[1]))
name =("{0}_{1}".format(row[0], row[1]))
arcpy.Rename_management(fc, name)

Our field data is collected on a trimble. Each time we start to collect we open a new file, so everyday its a new file, meaning the date is always the same as is the editor (we have our own units). So I made a complicated model that buffered our points and lines into polygons, then merged them with our polygon layer, than did some spatial joins to slops and aspect layers than calculates the slope field into a text value (Steep or whatever), than there is a bunch of other things but the output is always the same file name, so I made this last script to run and rename each file based on the park the data was collected in (one of the joins is to a park layer) the editor, and the date. It worked really well and was fun to learn.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...