Select to view content in your preferred language

Python -?- FindAndReplaceWorkspacePaths for directory and all subdirectories?

2113
1
07-20-2010 12:52 PM
JeffPickles
Deactivated User
I'm looking to update a bunch of file references in MXDs througout a directory and all included subdirectories. This is a project I've been delaying until the ArcPy module was available, but now that it's here I'm having an issue getting it to work with those pesky subdirectories.

In the ArcGIS 10.0 help file, there is this topic regarding the Python FindAndReplaceWorkspacePath function.

I'm looking to tweak this code (example 2 from that referenced link)...

import arcpy, os
folderPath = r"C:\Project"
for filename in os.listdir(folderPath):
    fullpath = os.path.join(folderPath, filename)
    if os.path.isfile(fullpath):
        basename, extension = os.path.splitext(fullpath)
        if extension.lower() == ".mxd":
            mxd = arcpy.mapping.MapDocument(fullpath)
            mxd.findAndReplaceWorkspacePaths(r"C:\Project\Data", r"\\ComputerName\Project\Data")
            mxd.save()
del mxd


This code only seems to work for C:\Project and does not touch any MXDs in subdirectories.

How can I tweak this to include subdirectories in the process?
0 Kudos
1 Reply
GünterDörffel
Frequent Contributor
Hi Jeff,

I use the os.walk function to do any recursive directory "thingies" ...

Here a stub-code sample you might find useful:
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# ListMXDs.py
# 
# Usage: ListMXDs <Directory to search>
# ---------------------------------------------------------------------------
import sys, os
#path to search - here hardcoded
theDirectory=r'C:\Archive'
#if parsed as argument
#theDirectory = sys.argv[1]
#File-Pattern to search
thePattern = "mxd"
#cycle through the directory and find all Files of type ...
for root, folders, AllFiles in os.walk(theDirectory):
    print "********** \nWorking on folder "+root+"\n**********"
    # now find mxds and print their names        
    for oneFile in AllFiles:
        #only do something if it is an mxd
        if oneFile.endswith(thePattern):
            print oneFile


Regards
Guenter
0 Kudos