【问题标题】:ArcGIS python code to change path to relative for all subdirectoriesArcGIS python代码将路径更改为所有子目录的相对路径
【发布时间】:2020-05-14 18:09:51
【问题描述】:

对python很陌生,但在大学有一些编码经验。当我准备 GIS 项目数据库以从本地托管过渡到云托管(刚开始在家工作)时,我正在尝试找到一种方法将每个 mxd 文件中的路径从绝对更改为相对。我发现了 2 个我认为可能有效但无法让它们一起工作的代码片段。 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
...             

【问题讨论】:

    标签: python path gis arcgis


    【解决方案1】:

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

    尝试以下方法:

    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()
    

    【讨论】:

    • 这行得通,但是我不得不更改一行。在第 18 行出现运行时错误。无效的 MXD 文件名。所以我改了mxd = arcpy.mapping.MapDocument(file**Path**)
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多