Writing Python script to batch import .mxd to .aprx

aprxarcgis-proarcpymxd

I'm attempting to write a Python script that finds all of the .mxd files in my local directories, imports them into a blank .aprx, and then saves them as an .aprx file.

I'm able to successfully locate the files and import them into a blank project, but somewhere along the line several of the .mxds are getting saved into one .aprx when I want one .mxd per .aprx file. For example, I want MXD1 to save into APRX1, but what is happening is MXD1, MXD2, and MXD3 are all being saved into APRX1.

My script is pasted below –

import os
import pathlib
import arcpy

ogDir = input('Directory to search for .mxds: ')
dirContents = os.listdir(ogDir)
aprx = arcpy.mp.ArcGISProject(r'C:\Users\M\Documents\mxd_test\blank\blank.aprx')

for folder_path, subfolders, filenames in os.walk(ogDir):
    for file in filenames:
        if file[-4:] == '.mxd':
            filePath = pathlib.Path(folder_path) / file
            mxd = file[:-4]
            aprx.importDocument(filePath)
            aprx.saveACopy(folder_path + '\\' + mxd + '.aprx')

Best Answer

Try changing where you've set the APRX variable. You'll see I moved the creation of it into your loop, at the same time you're importing into it and saving it. As your code is, it will probably append every single MXD it finds into the single existing variable you have (as you never clear it out). So the first run will save an .aprx with 1 imported MXD, the next .aprx will have the first and second, and so-on.

import os
import pathlib
import arcpy

ogDir = input('Directory to search for .mxds: ')
dirContents = os.listdir(ogDir)

for folder_path, subfolders, filenames in os.walk(ogDir):
    for file in filenames:
        if file[-4:] == '.mxd':
            aprx = arcpy.mp.ArcGISProject(r'C:\Users\M\Documents\mxd_test\blank\blank.aprx')
            filePath = pathlib.Path(folder_path) / file
            mxd = file[:-4]
            aprx.importDocument(filePath)
            aprx.saveACopy(folder_path + '\\' + mxd + '.aprx')
Related Question