AnsweredAssumed Answered

How can I use a layer name with spaces in python?

Question asked by lindsay.raabe_FPCWA on Sep 14, 2018
Latest reply on Sep 16, 2018 by lindsay.raabe_FPCWA

Hi All. I'm trying to run the below python code with no luck. The 2 layers listed on line 20 are referenced again on line 37 when I attempt to cycle through their extents. The code should pull the extents and apply them to the data frame. The issue is that the list at line 20 won't work unless there are no spaces in the layer names. If enclose the names in "..." then the code is "syntax error free" but fails at line 37 when trying to extract the extent of a string object instead of a layer. How can I work around this (would prefer to not have to rename my layers in the mxd!). 

import arcpy
from arcpy import env, mapping
from bisect import bisect

#input parameters;
Plantation = arcpy.GetParameter(0)
ForestID = arcpy.GetParameter(1)
CommonName = arcpy.GetParameter(2)
PYear = arcpy.GetParameter(3)
OpCode = arcpy.GetParameter(4)

#variables;
title1 = Plantation + " PLANTATION"
title2 = Plantation + "\r\nPLANTATION"
title3 = Plantation + " (" + CommonName + ")"
title4 = Plantation + " P" + PYear + " AREA STATEMENT"
mxd = mapping.MapDocument("CURRENT")
elements = mapping.ListLayoutElements(mxd)
layers = mapping.ListLayers(mxd)
HTL_layer_list = ["Entered In GeoMaster", "Entered In GeoMaster Archive"]
dflist = arcpy.mapping.ListDataFrames(mxd, "")
opcode_exp1 = "EnteredInGeoMaster IS NOT NULL AND Ops_Code = '" + OpCode + "'"
opcode_exp2 = "Ops_Code = '" + OpCode + "'"

    if lyr.name == "Entered In GeoMaster":
        lyr.definitionQuery = opcode_exp1
        arcpy.AddMessage(lyr.name + " definition query updated")
       
    elif lyr.name == "Entered In GeoMaster Archive":
        lyr.definitionQuery = opcode_exp2
        arcpy.AddMessage(lyr.name + " definition query updated")
        # get current map extent
        xmin, xmax = dflist[0].extent.XMin, dflist[0].extent.XMax
        ymin, ymax = dflist[0].extent.YMin, dflist[0].extent.YMax
        # loop through def query layer extents and create one extent to fit them all
        for HTL_lyr in HTL_layer_list:
            HTL_ext = HTL_lyr.getExtent()
            if HTL_ext.XMin < xmin:
                xmin = ext.XMin
            if HTL_ext.YMin < ymin:
                ymin = ext.YMin
            if HTL_ext.XMax > xmax:
                xmax = ext.XMax
            if HTL_ext.YMax > ymax:
                ymax = ext.YMax
        # set df extent to new extent
        dflist[0].extent = arcpy.Extent(xmin, ymin, xmax, ymax)

Outcomes