Select to view content in your preferred language

Change datasource in .lyr files in specific folder

10012
20
10-12-2017 12:48 PM
JoseSanchez
Frequent Contributor

Good afternoon everyone,

We have a folder  with 175 .lyr files. All .lyr files are pointing to an SDE instance and we need to change each lyr data source to point to another SDE instance.

I am looking for a way to do that in python where I can loop through all files in the folder and change their datasource.

Thanks

0 Kudos
20 Replies
JoshuaBixby
MVP Esteemed Contributor

Sharing with https://community.esri.com/community/developers/gis-developers/python?sr=search&searchId=998cdb5b-d7...‌ since this seems more an ArcPy question than ArcGIS API for Python.

MicahBabinski
Frequent Contributor

Hi Jose,

As with anything arcpy related, the documentation is your friend. Being able to read through the documents and figure out how to do this kind of thing is essential to becoming a good python/arcpy scripter. Have a look at this topic and see what you can do:

Updating and fixing data sources with arcpy.mapping—Help | ArcGIS for Desktop 

The generalized process I would do is:

  1. List all .lyr files using os.listdir() or arcpy.ListFiles("*.lyr")
  2. Create a top-level layer object from the layer file
  3. Loop through each sublayer, determine if it supports the data source property
  4. Update the data source
  5. Save the top-level layer object

Good luck!

JoseSanchez
Frequent Contributor

Hello everyone,

I was able to browse all .lyr files, but when the script runs the line replaceDataSource, nothing happens.

#

# List all lyr files

#

 

lyrFileList = arcpy.ListFiles("*.lyr");

arcpy.env.workspace = newSdePath  

for lyrFile in lyrFileList:

   print lyrFile

   lyr = arcpy.mapping.Layer(os.path.join(folderpathLayerFiles,lyrFile))

   if lyr.supports("DATASOURCE"😞

      print lyr.dataSource

      print lyr.datasetName

      value = "xxx.xxx." + lyr.datasetName.split(".")[1]

      if arcpy.Exists(value):

         print "Replace Datasource for " + value

         lyr.replaceDataSource(newSdePath, "SDE_WORKSPACE", "", True)

0 Kudos
MichaelVolz
Esteemed Contributor

Are all the lyr files for single SDE feature classes or do you have some group lyr files?  I mention this because I created a script where I had to change the source of lyr files and I had to drill down to each individual lyr in the group lyr file when I encountered a group lyr file.

Did you validate that the newSdePath is valid and would connect to the new SDE database in ArcCatalog?

0 Kudos
MicahBabinski
Frequent Contributor

Hi Jose,

If the dataset names are the same try:

lyr.replaceDataSource(newSdePath, "SDE_WORKSPACE", lyr.datasetName, True)

or:

lyr.replaceDataSource(newSdePath, "SDE_WORKSPACE", "#", True)‍

The empty double-quotes for the dataset_name parameter could be causing your validation to fail.

Micah

JoseSanchez
Frequent Contributor

Hi Michael,

Each  .lyr files points to one single feature class. And feature classes are stand alone feature classes or part of a feature dataset.

To populate newSdePath I just copy/pasted the value form ArcCatalog.

newSdePath = r"Database Connections\SQL Prod.sde"

Thanks

0 Kudos
MichaelVolz
Esteemed Contributor

Are you showing all the code for the script?  I ask because I don't see where you set the value of newSdePath.  I just see that arcpy.env.workspace is set to newSdePath which would be empty if you have not set that value in code.

0 Kudos
DanPatterson_Retired
MVP Emeritus

in all the examples in the listed http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-mapping/updatingandfixingdatasources.htm help topic, they show an *mxd being loaded, stuff being done, then a copy of the mxd being saved... I wonder...

JoseSanchez
Frequent Contributor

Hi again,

below is a copy/paste of most of the code:

import arcpy
import sys, traceback, string, os
import logging
import datetime
import time
import calendar


folderpathLayerFiles =  r"\\....LayerFiles"

folderpathSymbology =  r"\\....Symbology"


arcpy.env.workspace = folderpathLayerFiles

newSdePath = r"xxxx.sde"


def CreateErrorFlag(aJobName):
    try:
        commandLine = "trap.cmd " + aJobName
        aresult = os.system(commandLine)
        if aresult > 0:
            sys.exit(1)
    except:
        return (aresult)
        print "error"
        sys.exit(1)

try:
    logging.info(':=================================== START LOGGING')
    logging.info("Start Script: " + time.strftime("%c"))

    print "Start Script: " + time.strftime("%c")

    #
    # List all lyr files
    #


    lyrFileList = arcpy.ListFiles("*.lyr");
   
    arcpy.env.workspace = newSdePath

    for lyrFile in lyrFileList:
        print lyrFile
      
        lyr = arcpy.mapping.Layer(os.path.join(folderpathLayerFiles,lyrFile))
        if lyr.supports("DATASOURCE"):
            print lyr.dataSource
            print lyr.datasetName

            value = "xxxx.xxx." + lyr.datasetName.split(".")[1]
         
            if arcpy.Exists(value):
                print "Replace Datasource for " + value
                #lyr.findAndReplaceWorkspacePath(find_workspace_path=lyr.workspacePath, replace_workspace_path=newSdePath)

                lyr.replaceDataSource(newSdePath, "SDE_WORKSPACE",lyr.datasetName, True)

0 Kudos