[GIS] How to access all mxd files in a folder

arcpymsdmxdpython

I'm a beginner to Python and am trying to figure out how I can access several mxds in a folder. For example, when I want to use the AnalyzeforMSD function in ArcGIS:

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\ReadyForMSD.mxd")
analysis = arcpy.mapping.AnalyzeForMSD(mxd)

How can I define a folder with mxds as a path, e.g. C:\Projects\data, and analyze all the mxds in it?

import os, arcpy

directory = r"C:\Project"
 for root, dirs, files in os.walk(directory):
   for myFile in files:
        fileExt = os.path.splitext(myFile)[1]
        if (fileExt == ".mxd"):
            fullPath = os.path.join(root, myFile)
            print myFile

            myMap = arcpy.mapping.MapDocument(fullPath)
            analysis = arcpy.mapping.AnalyzeForMSD(myMap)

 for key in ('messages', 'warnings', 'errors'):
 print "----" + key.upper() + "---"
 vars = analysis[key]
 for ((message, code), layerlist) in vars.iteritems():
print "    ", message, " (CODE %i)" % code
print "       applies to:",
for layer in layerlist:
    print layer.name,
print

Best Answer

Use os.walk to walk through defined directory, and .endwith to find all mxd's within directory/sub directory, see example below:

import arcpy, os

for root, dirs, files in os.walk(r"C:\Project"):

        for f in files:
            if f.endswith(".mxd"):
                mxd = root + '\\' + f
                analysis = arcpy.mapping.AnalyzeForMSD(mxd)
                # may want to append your analysis info to a text file after here
Related Question