0

When I run the following code in an open mapdocument, it executes and does what I want it to, replace the datasource of the Indianacounty_shp layer with the County_Boundary feature class.

import arcpy, os, datetime
mxd = arcpy.mapping.MapDocument("CURRENT")
        lyr = arcpy.mapping.Layer('Indianacounty_shp')
        lyr.replaceDataSource(r"N:\3_PLANNING\6_GIS\GIS Data\Indiana_County_Database_201201.gdb", "FILEGDB_WORKSPACE", 'County_Boundary', True)
        mxd.save()

I'm attempting to write a script the have it run through a list of mxd's in a folder, and do the same thing for all of them. When I run the following script, i get a "Runtime error : Object: CreateObject Layer invalid data source"

import arcpy
import arcpy.mapping
import os
import sys
from arcpy import env
import string

env.workspace = r"N:\3_PLANNING\6_GIS\GIS Projects\CompPlanMaps\test"
for mxd in arcpy.ListFiles("*.mxd"):
    mapdoc = arcpy.mapping.MapDocument("N:/3_PLANNING/6_GIS/GIS Projects/CompPlanMaps/test/" + mxd)
    lyr = arcpy.mapping.Layer('Indianacounty_shp')
    lyr.replaceDataSource("N:/3_PLANNING/6_GIS/GIS Data/Indiana_County_Database_201201.gdb", "FILEGDB_WORKSPACE", 'County_Boundary', True)
    mxd.save()
del mxd, addLayer, mapdoc

I've tried with both / or \ in the file names, and with and without the r in front. Any ideas what I'm doing wrong?

1 Answer 1

1

This line will work in your open MXD because it can find a layer called 'Indianacounty_shp'

lyr = arcpy.mapping.Layer('Indianacounty_shp')

However, when you get to the Table of Contents for each MXD you open from your script you will need to iterate through the layers and search for any called 'Indianacounty_shp' before attempting to do the same thing (in some I suspect that layer may not exist). The untested code below should do it.

for lyr in arcpy.mapping.ListLayers(mxd, 'Indianacounty_shp'):
    lyr.replaceDataSource("N:/3_PLANNING/6_GIS/GIS Data/Indiana_County_Database_201201.gdb", "FILEGDB_WORKSPACE", 'County_Boundary', True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.