I have inherited a number of ArcMap projects, where the data sources have been broken by various people's file admin. Shapefiles have been moved from one folder to another, but subdirectory organisation remains the same. I am trying to fix the links using updateConnectionProperties. I use the following code on individual shapefiles, but cannot get the desired result.
variable "newsource" returns a correct filepath (printed by line 7) but I think line 8 is the problem as "not possible" is printed. No errors are returned. Any help appreciated. Thanks
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Users\CAddison\Documents\ArcGIS\Test001.mxd")
for lyr in arcpy.mapping.ListLayers(mxd):
try:
oldsource = lyr.dataSource
newsource = oldsource[0:53]+str("\\NEW\\")+oldsource[65:]
print newsource
lyr.updateConnectionProperties(oldsource, newsource)
except:
print "not possible"
python 3 versus python 2. Try
print(newsource)
print("Not Possible")
Thanks Dan. Will try later, but since running the script resulted in newsource being printed and "not possible" also being printed, I'm not sure if this will fix the data links. Will try though, and thanks.
Could it be that updateConnectionProperties method is only for Pro aprx projects, not ArcMaP mxd?
Updating and fixing data sources with arcpy.mapping—ArcMap | Dokumentation (arcgis.com)
We've had mixed success with findAndReplaceWorkspacePath for mxds.
import arcpy, os
arcpy.env.overwriteOutput = True
# get mxd
mxd_pth = r"W:\GISRequests\DCI\2016MJ\2016_MJ_project.mxd"
mxd = arcpy.mapping.MapDocument(mxd_pth)
oldpth = r"W:\GISRequests\DCI\2016MJ"
newpth = r"W:\GISRequests\DCI\2016MJp\2016 MJ Project Geodatabase.gdb"
featureclasses = arcpy.mapping.ListLayers(mxd)
for lyr in featureclasses:
lyrname = lyr.name
if lyr.supports("DATASOURCE"):
if lyr.dataSource == os.path.join(oldpth, lyrname):
arcpy.AddMessage("Updating: {}".format(lyrname))
lyr.findAndReplaceWorkspacePath(oldpth, newpth)
mxd.save()
del mxd
Thanks a lot. This looks really useful, will give it a whirl. Pardon my ignorance, but does your "newpth" have to direct to a .gdb? Can this be used for individual .shp as I'm trying to do, where the .shp hasn't been added to a .gdb?
No, it can be a folder if needed.