- Programming ArcGIS with Python Cookbook(Second Edition)
- Eric Pimpler
- 413字
- 2021-07-16 13:32:24
Finding broken data sources in your map document and layer files
Broken data sources are a very common problem with map document files. You can use arcpy.mapping
to identify data sources that have moved, been deleted, or changed in their format.
Getting ready
In ArcMap, a broken data connection is signified by a red exclamation point just before the layer name. This is illustrated in the following screenshot. The ListBrokenDataSources()
function in arcpy.mapping
returns a list of layer objects from a map document or layer file that have a broken data connection:

How to do it…
Follow these steps to learn how to find broken data sources in a map document file.
- Open
C:\ArcpyBook\Ch3\Crime_BrokenDataLinks.mxd
in ArcMap.You will see that each of the data sources have been broken. In this case, the data has been moved to another folder, but you'd see the same indicator if the data had been deleted or migrated to a different format. For example, it is not uncommon to convert data from a personal geodatabase to a file geodatabase:
- Close ArcMap.
- Open IDLE and create a new script window.
- Import the
arcpy.mapping
module:import arcpy.mapping as mapping
- Reference the
Crime_BrokenDataLinks.mxd
map document file:mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch3\Crime_BrokenDataLinks.mxd")
- Get a list of the broken data sources:
listBrokenDS = mapping.ListBrokenDataSources(mxd)
- Iterate the list and print out the layer names:
for layer in listBrokenDS: print(layer.name)
The output will be printed as follows:
District_Crime_Join Bexar_County_Boundary District_Crime_Join Bexar_County_Boundary Bexar_County_Boundary Texas_Counties_LowRes School_Districts Crime_surf Bexar_County_Boundary Crime2009Table
- Save your script as
FindFixBrokenData.py
in thec:\ArcpyBook\Ch3
folder. - You can check your work by examining the
c:\ArcpyBook\code\Ch3\FindFixBrokenData.py
solution file.
How it works…
The ListBrokenDataSources()
function returns a Python list of Layer
objects that have a broken data source. We then use a for
loop to iterate this list and perform some sort of action for each layer. In this case, we printed out the layer names simply to illustrate the data returned by this function. In a later recipe, we'll build on this code by fixing these broken data sources.
There's more…
In addition to returning a list of broken data sources from a map document file, the ListBrokenDataSources()
function can also find broken data sources in a (.lyr
) layer file. Simply pass the path to the layer file to have the function examine the file for broken data sources. Keep in mind that these functions are not needed with Map
or Layer
packages, since the data is bundled with these files unlike a layer file.