用于将所有子目录的路径更改为相对路径的ArcGIS python代码

2024-09-30 01:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

对python非常陌生,但在大学里有一些编码经验。我正在尝试找到一种方法,将每个mxd文件中的路径从绝对更改为相对,同时准备我的GIS项目数据库,以从本地托管转换为云托管(刚刚开始在家工作)。我发现了两个我认为可能有效但无法让它们协同工作的代码片段。来自ArcGIS的代码只在一个文件夹上工作,我希望它在根目录中的每个子目录上运行。谢谢你的帮助

ArcGIS Python部分

import arcpy, os

#workspace to search for MXDs
Workspace = r"c:\Temp\MXDs"
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:\\user\projects'
... pattern = "*.mxd"
... 
... for path, subdirs, files in os.walk(root):
...     for name in files:
...         if fnmatch(name, pattern)
...             mxdList = arcpy.ListFiles
...             

Tags: path代码inimportmapforosworkspace
1条回答
网友
1楼 · 发布于 2024-09-30 01:18:32

此任务不需要使用fnmatch模块。arcpy.ListFiles('*.mxd')函数中的通配符就足够了。不要通过files循环,而是通过os.walk(root)循环subdirs

请尝试以下操作:

import arcpy, os

root = r'C:\user\projects'
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()

相关问题 更多 >

    热门问题