cschieffer_newcom

Python script to loop through folders and replace data sources running slow

Discussion created by cschieffer_newcom on Jan 9, 2020
Latest reply on Jan 10, 2020 by cschieffer_newcom

Hello,

I have a python script that will loop through all folders and sub folders in a specified directory searching for mxd's with a specific data source. If the data source is found it will replace that data source with a new one.

 

The script I have works, but it is very slow. I did it on a test folder with 3 sub folders and a total of 9 maps. It took a little over 30 minutes. I am far from an expert on python scripting - is there anything anyone can see that I am doing wrong in my script that might cause it to run slow, or is there a better way to achieve what I'm trying to?

 

Thank you.

import arcpy, os, fnmatch, sys

def find(pattern, path=os.getcwd()):
    for path, dirs, files in os.walk(path):
        for filename in files:
            if fnmatch.fnmatch(filename, pattern): yield os.path.abspath(os.path.join(path, filename))

for mxdname in find('*.mxd',r'D:\GIS Projects\TEST'):
    mxd=arcpy.mapping.MapDocument(r'{}'.format(mxdname))
    print mxdname
    for lyr in arcpy.mapping.ListLayers(mxd):
        if lyr.supports("DATASOURCE"):
            if lyr.dataSource == r"C:\GIS\Cty\2017 Orthos\2017_Orthos.gdb\Orthos_2017":
                lyr.replaceDataSource(r"D:\GIS\Cty\Orthos\County_Orthos.gdb", "FILEGDB_WORKSPACE", "County_Orthos")
                lyr.name = "County_Orthos"
                print 'Replaced Orthos'
    mxd.save()
    del mxd

Outcomes