A common scenario in many organizations involves the movement of data from one workspace to another or from one workspace type to another. When this happens, any map documents or layers that reference these data sources become broken. Finding each of these data sources can be a huge task if undertaken manually. Fortunately, you can create a geoprocessing script that will find all broken data sources in a folder or list of folders.
In this recipe, you will learn how to recursively search directories for map document files, find any broken data sources within these map documents, and write the names of the broken data layers to a file.
Follow these steps to learn how to find all broken data sources in all map documents in a folder:
arcpy
and os
packages:import arcpy.mapping as mapping, os
f = open('BrokenDataList.txt', 'w')
c:ArcpyBook
folder to use in the os.walk()
method along with a for
loop to walk the directory tree:for root,dirs,files in os.walk("C:ArcpyBook"):
for
loop, create a second for
loop that loops through all the files returned and create a new filename
variable. Remember to indent the for
loop inside the first for
loop:for name in files: filename = os.path.join(root, name)
if ".mxd" in filename: mxd = mapping.MapDocument(filename) f.write("MXD: " + filename + " ") brknList = mapping.ListBrokenDataSources(mxd) for brknItem in brknList: print "Broken data item: " + brknItem.name + " in " + filename f.write(" " + brknItem.name + " ")
print
statement to indicate that you are done and close the file:print("All done") f.close()
c:ArcpyBookcodeCh3ListBrokenDataSources.py
solution file.This script uses a combination of methods from the Python os
package and the arcpy.mapping
package. The os.walk()
method walks a directory tree and returns the path, a list of directories, and a list of files for each directory starting with a root directory that you have defined as the c:ArcpyBook
directory. This root directory could have been any directory. The os.walk()
method returns a three item tuple consisting of the root directory, a list of directories immediately contained within that root, as well as a list of files immediately contained within the root. We then loop through this list of files and test each one to see if it contains the .mxd
string, which indicates a map document file. Files identified as map documents have their filenames written to a text file, and a new MapDocument
object instance is created. The ListBrokenDataSources()
method is then used with a reference to the map document to generate a list of broken data sources within the file, and these broken data sources are written to the file as well.