import arcpy, sys, os, fnmatch dir = sys.argv[1] # directory to search old = sys.argv[2] # old feature class path/name to replace new = sys.argv[3] # new feature class path/name # go to the directory and get a list of the files filelist = os.listdir(dir) # get that file list and for each name.... for filename in filelist: # look for any .lyr files if fnmatch.fnmatch(filename, '*.lyr'): arcpy.AddMessage(filename + " is a layer file") # create a layer object from the .lyr file lyrfile = arcpy.mapping.Layer(dir + '\\' + filename) arcpy.AddMessage(filename + " is now a layer object") arcpy.AddMessage(old) arcpy.AddMessage(new) lyrfile.findAndReplaceWorkspacePath(old, new) arcpy.AddMessage("fixed data source") arcpy.AddMessage("finito!!!") del filename, filelist, dir, old, new, lyrfile
I have a bunch of .lyr files that point to a directory that's been moved.
I'm trying to programmatically re-link them to the new location (hopefully to a UNC location like \\server\folder instead of W:\folder)
so my code looks like this:import arcpy, sys, os, fnmatch dir = sys.argv[1] # directory to search old = sys.argv[2] # old feature class path/name to replace new = sys.argv[3] # new feature class path/name # go to the directory and get a list of the files filelist = os.listdir(dir) # get that file list and for each name.... for filename in filelist: # look for any .lyr files if fnmatch.fnmatch(filename, '*.lyr'): arcpy.AddMessage(filename + " is a layer file") # create a layer object from the .lyr file lyrfile = arcpy.mapping.Layer(dir + '\\' + filename) arcpy.AddMessage(filename + " is now a layer object") arcpy.AddMessage(old) arcpy.AddMessage(new) lyrfile.findAndReplaceWorkspacePath(old, new) arcpy.AddMessage("fixed data source") arcpy.AddMessage("finito!!!") del filename, filelist, dir, old, new, lyrfile
but when I run it - I get messages saying that something is happenning (all my addMessages). But when it comes to actually re-mapping my datasource, well, nothing happens. When I re-add the .lyr files to my mxd and check the data source, it doesn't change. It's still the old datasource.
any help???
looks like I forgot to save
lyrfile.save()
import arcpy layer1 = arcpy.mapping.Layer(r"C:\Temp\NE_States.lyr") layer1.findAndReplaceWorkspacePath(r"C:\Temp", r"\\JBarrette\Temp") layer1.saveACopy(r"C:\Temp\NE_States2.lyr") print layer1.dataSource >>\\Jbarrette\Temp\NE_Lakes.shp
This script works fine when run from IDLE (or from the Python window):import arcpy layer1 = arcpy.mapping.Layer(r"C:\Temp\NE_States.lyr") layer1.findAndReplaceWorkspacePath(r"C:\Temp", r"\\JBarrette\Temp") layer1.saveACopy(r"C:\Temp\NE_States2.lyr") print layer1.dataSource >>\\Jbarrette\Temp\NE_Lakes.shp
Are you attempting to change the dataset name in any way? FindAndReplaceWorkspacePath only works on the workspace path.
Jeff