Wednesday 30 March 2016

arcpy - ValueError error from lyr.replaceDataSource()?


I'm trying to write a script that allows me to look through map documents and replace each layer's data source in each map document. Everything is working logically I believe, and all my loops are working as they should. The datasets that are referenced exist. Yet, I am getting this error :




Traceback (most recent call last): File "C:\Python27\ArcGIS10.1\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript exec codeObject in main.dict File "C:\Users\Daimon Nurse\Desktop\DFMPROJECT\Scripts\editmapdocument8.py", line 18, in Lyr.replaceDataSource(workspace_path, workspace_type, dataset_name) File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\utils.py", line 181, in fn_ return fn(*args, **kw) File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy_mapping.py", line 680, in replaceDataSource return convertArcObjectToPythonObject(self._arc_object.replaceDataSource(*gp_fixargs((workspace_path, workspace_type, dataset_name, validate), True))) ValueError: Layer: Unexpected error



This is the code I am using:


 import arcpy
import os

PATH2 = r"C:\Users\Daimon Nurse\Desktop\DFMPROJECT"
arcpy.env.workspace = PATH2
arcpy.env.overwriteOutput=True


for file in arcpy.ListFiles("*.mxd"):
filePath = os.path.join(PATH2,file)
MapDoc = arcpy.mapping.MapDocument(filePath)
lyrList = arcpy.mapping.ListLayers(MapDoc)
i = 1
for Lyr in lyrList:
print Lyr
workspace_path = r"C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFM"
workspace_type = "FILEGDB_WORKSPACE"
dataset_name = 'Zone{0}'.format(i)

print dataset_name
print workspace_type
print workspace_path
print os.path.join (workspace_path, dataset_name)
Lyr.replaceDataSource(workspace_path, workspace_type, dataset_name)
i = i + 1

These are the printed results on the first iteration for dataset_name, workspace_type, workspace_path and os.path.join respectively:


Zone1
FILEGDB_WORKSPACE

C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFM
C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFM\Zone1

Answer



The problem was I was listing the dataset in the replacedatasource function when I really just needed to list the name of the feature class itself. for example:


for table in arcpy.mapping.ListTableViews(mxd):
print table.name
filename1 = table.name
table.replaceDataSource(PATH, workspacetype, filename1)
print "REPLACED!"

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...