AnsweredAssumed Answered

looking for advice with lyr.replaceDataSource()

Question asked by euloki on Mar 22, 2018
Latest reply on Mar 23, 2018 by euloki

Hi there,

This is an evolving script.  I am essentially teaching myself but it's like stumbling around in the dark.  

I have a butt-load of mxd's whose layers' datasources are being changed, both in location and in feature class name (for the most part). I managed to write a script that would walk through a directory and list each mxd, layer name, layer datasource path and layer feature class name and write it to a csv.  That worked fine.  

Now I'm looking to use an altered form of that list to automate the lyr.replaceDataSource() method.

I have got part of the code working, but when it comes to actually changing the datasource it comes up a dud.  


                                          Maybe it's my logic. Maybe the code is too simplistic.  I dunno.   


Now, I have tested it by hardcoding the paths and values in and it works hunky-dory both with single and double quotes.  (thanks to the advice from some helpful people like yourself!)


When I try to use the lists I don't get very far. Maybe someone out there can see what I am doing wrong or leaving out?  any advice would be great!


Here's what I got:

# This script reads a list in csv format and assigns them to variables to be
# used in the lyr.replaceDataSource method. It will then be used to replace old paths with
# new sources and change each layer's feature class and layer name for each map in the directory.
# **This is just a test code for now**

import csv
import arcpy

#     set up blank lists for data

oldP,newF,newL = [],[],[]

#     read data from file and store in lists

with open(r"C:\hardcode_to_Path\dsListTEST.csv", "rb") as dsList:
     r= csv.reader(dsList,delimiter=",")
     for i,row in enumerate(r):
          if i>0:                  #skip the header
#     replace the existing datasource with the new path, feature class name and layer name.
               mxd = arcpy.mapping.MapDocument(r"hardcode_to_testMap.mxd")
               for lyr in arcpy.mapping.ListLayers(mxd):
                    if lyr.supports("DATASOURCE"):
                         if lyr.dataSource == oldP:
                              lyr.replaceDataSource(r"Hardcode_to_new_location","None",newF, True)
                     = newL
                              print lyr.dataSource
               del mxd

The list append works... and so does the mxd.saveACopy.  

BUT the important part in between does not do anything.  DUD.