Select to view content in your preferred language

Python script to automate Save as layer file...

3158
3
09-16-2011 04:26 AM
JosephJira
New Contributor
Hello all. Searched the forums, but could not find any issues that addressed my problem.

I would like to create a python script to limit a feature class (or layer) with a definition query and save it as a layer file, similar to if you wrote a definition query for a layer and then right clicked in the TOC and used the "Save As Layer File...".

I have done this in python using SelectLayerByAttribute_management (to limit the layer using a query) and SaveToLayerFile_management (to save to a layer file). This works, however the layer file uses a selection set to define the features and not a definition query to define the features. There is big difference, if features are added to the feature class, they will not be displayed with the layer file, because it is based on a selection, not a query.

I'll be thankful for any help or comments.
Tags (2)
0 Kudos
3 Replies
AndrewChapkowski
Esri Regular Contributor
Use the MakeFeatureLayer_management() and specify the where clause, then save that layer to disk.

import arcpy
import os
arcpy.MakeFeatureLayer_management(States, States_Layer, "\"State_Name\" = 'Alabama'")
arcpy.SaveToLayerFile_management(States_Layer, PathToLayer + os.sep + "layername.lyr", "")


Hope this helps.
0 Kudos
JosephJira
New Contributor
Thanks for your quick reply.

My code is essentially the same as you suggest, however maybe I was not clear about what I want to do. In your example, say that you added another state called Alabama to your feature class. The layer file will not recognize the new state that you added, because the layer file is based on a SELECTION, not a query. In Layer Properties in the Definition Query tab you can verify this -- *Layer based on a selection set containing 1 features.

If you save AS layer file (right click on the layer "Save As Layer File...") in the TOC the layer file will recognize the new feature because it is based on a Definition Query.

Again, thanks for your reply.
0 Kudos
AndrewChapkowski
Esri Regular Contributor
Try this, if you use the Layer object you can do what you want, where the where clause appears in the layer properties.

import arcpy
from arcpy import mapping
fc = r"C:\fGDB.gdb\states"
statesLayer = "tempLayer"
where = "\"State_Name\" = 'Alabama'"
arcpy.MakeFeatureLayer_management(fc,statesLayer)
lyr = mapping.Layer(statesLayer)
lyr.definitionQuery = where
lyr.saveACopy(r"c:\temp\statelayer.lyr")
del lyr
del fc
del statesLayer
del where
0 Kudos