Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)

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)
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?

share|improve this question

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)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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