Using Python to Export all MXD's in a Directory

8473
4
02-24-2013 02:49 AM
JamesHockey
New Contributor
I was just wondering if anyone knew how I could use Python to open and export all *.mxd documents in a directory (as a pdf). At the moment I can open specific *.mxd documents and export them. If I could have a code however that looks in a directory and could open all the files within it and export all the maps it would save me a lot of time.
Tags (2)
0 Kudos
4 Replies
CraigPoynter
Occasional Contributor III
Try using model builder and one of the iterate functions to list and iterate MXD files in a workspace / directory and export to PDF.

If you have subfolders have a look into the arcpy Walk function to do recursive searches for MXD files.

Regards,

Craig
0 Kudos
JeffMoulds
Esri Contributor
ModelBuilder will work, but if you want to do it in Python, like your post says, all you need is something like this that loops through all MXDs in a folder, then exports them to PDF.
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)
            arcpy.mapping.ExportToPDF(mxd, basename + '.pdf')
SeanConlon
New Contributor II

Jeff,  this works almost perfectly. In testing, it created PDF's out all my MXD's in a folder,  but is it possible to output to a different folder?  I tried messing around with your code but I don't have enough knowledge to get it to work.

thanks

Sean

0 Kudos
CraigPoynter
Occasional Contributor III

Hi Sean,

Try something like:

import arcpy, os

folderPath = r"C:\Project"

outFolder = r"C:\Project\PDFs" ## create an output folder

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)

arcpy.mapping.ExportToPDF(mxd, outFolder + basename + '.pdf')

You will probably need to create ‘PDFs’ folder before running script.

Regards,

Craig

C. Poynter

Information Technology Officer (Spatial Analysis) | Research Office, Spatial Data Analysis Network (SPAN)

Charles Sturt University

Boorooma Street

Wagga Wagga, NSW, 2678

Australia

Phone: +61 2 69332165

Fax: +61 2 69332735

Email: cpoynter@csu.edu.au<mailto:cpoynter@csu.edu.au>

www.csu.edu.au<http://www.csu.edu.au/>

0 Kudos