AnsweredAssumed Answered

How to save layer files and ignore special characters using python?

Question asked by RTanneka on Apr 30, 2019
Latest reply on May 1, 2019 by bixb0012

I'm trying to save all layers in my mxd as .lyr files using the script below. However, I'm getting an error because some layer names contain special characters (e.g. © : * )  and cannot be written into file names. How can I make sure special characters are ignored/replaced?

 

  1. import os  
  2. basepath = r'C:\Users\Anneka\CaBA_Data_Phase_5\Layers'  
  3. mxd = arcpy.mapping.MapDocument("CURRENT")  
  4. for lyr in arcpy.mapping.ListLayers(mxd):  
  5.      if lyr.isGroupLayer == True:  
  6.           grpPath = os.path.join(basepath, str(lyr))  
  7.           if not os.path.exists(grpPath):  
  8.                os.makedirs(grpPath)  
  9.      else:  
  10.           fn = os.path.join(basepath, str(lyr) + ".lyr")  
  11.           lyr.saveACopy(fn)  
  12.           print "Saved: " + fn  

Outcomes