Saturday 5 January 2019

python - Arcpy's replaceDataSource Error


I've checked the other answers here and none of the answers worked for me...



It's a "simple" matter of finding a layer by name in a map and changing it's datasource.


Here's my script:


    #-- New Source
newSource = os.path.join(currDir, lyrZones + "_Dep" + dirNum + ".shp")

#-- Validation
if arcpy.Exists(newSource):
print "The new source exists!"
else:
print "Not found!"


#-- Find the layer and change its source
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.name == lyrZones:
print "Layer found!"
print layers.dataSource
print " Replacing source..."
lyr.replaceDataSource(currDir, "SHAPEFILE_WORKSPACE", newSource)
print lyr.dataSource


I run it from a python script outside ArcGIS.


enter image description here


You can see that the source exists, the layer is found, I can access it's datasource by printing it, but the lyr.replaceDataSource causes an error (Unexpected error... doesn't help much...)


I've been working at it for 4-5 hours now and I'm short of solutions to try. Any idea what can cause the crash?



Answer



I know this is pretty old, but I just encountered this same issue and was surprised by the lack of solutions out there. The solution is so simple, but you'd have no way of knowing it based on ESRI's practically non-existent help:


Don't include the shapefile extension. ...That's it.


newSource = os.path.join(currDir, lyrZones + "_Dep" + dirNum + ".shp")

Should read:



newSource = os.path.join(currDir, '{}_Dep{}'.format(lyrZones, dirNum))

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...