对Python很陌生,但在大学里有一些编码经验。当我准备我的 GIS 项目数据库以从本地托管过渡到云托管(刚开始在家工作(时,我正在尝试找到一种方法将每个 mxd 文件中的路径从绝对更改为相对。我发现了 2 个我认为可能有效但无法让它们协同工作的代码。ArcGIS 中的代码仅适用于一个文件夹,我希望它在根目录中的每个子目录上运行。感谢您的帮助!
ArcGIS Python 部分
import arcpy, os
#workspace to search for MXDs
Workspace = r"c:TempMXDs"
arcpy.env.workspace = Workspace
#list map documents in folder
mxdList = arcpy.ListFiles("*.mxd")
#set relative path setting for each MXD in list.
for file in mxdList:
#set map document to change
filePath = os.path.join(Workspace, file)
mxd = arcpy.mapping.MapDocument(filePath)
#set relative paths property
mxd.relativePaths = True
#save map doucment change
mxd.save()
子目录代码
... from fnmatch import fnmatch
...
... root = 'C:\userprojects'
... pattern = "*.mxd"
...
... for path, subdirs, files in os.walk(root):
... for name in files:
... if fnmatch(name, pattern)
... mxdList = arcpy.ListFiles
...
您无需使用fnmatch
模块来完成此任务。arcpy.ListFiles('*.mxd')
函数中的通配符就足够了。与其循环files
,不如用os.walk(root)
循环subdirs
。
请尝试以下操作:
import arcpy, os
root = r'C:userprojects'
pattern = "*.mxd"
for path, subdirs, files in os.walk(root):
for subdir in subdirs: # loop through each subdirectory
fullpath = os.path.join(path, subdir)
print('Current directory: {}'.format(fullpath))
# set new workspace to combination of path and subdir
arcpy.env.workspace = fullpath
# search in the new workspace
mxdList = arcpy.ListFiles(pattern)
for file in mxdList: # apply the changes for each file
print('Processing: {}'.format(file))
# set map document to change
# here the variable file should be sufficient
mxd = arcpy.mapping.MapDocument(file)
# set relative paths property
mxd.relativePaths = True
# save map doucment change
mxd.save()