Walk (arcpy.da)
摘要
通过从上到下或从下到上遍历目录树,可在目录树中生成数据的名称。树中各字典/工作空间提供一个三元组:dirpath、dirnames 和 filenames。
讨论
Walk 函数在 ArcGIS 10.1 Service Pack 1 中可用。
Python 的 os 模块包括 os.walk 函数,可用于遍历目录树并查找数据。os.walk 是基础文件,它不识别数据库内容,例如,地理数据库要素类、表或栅格。arcpy.da.Walk 可用于为数据编目录。
语法
参数 | 说明 | 数据类型 |
top |
The top-level workspace that will be used. | String |
topdown | If topdown is True or not specified, the tuple for a directory is generated before the tuple for any of its workspaces (workspaces are generated top-down). If topdown is False, the tuple for a workspace is generated after the tuple for all of its subworkspaces (workspaces are generated bottom-up). When topdown is True, the dirnames list can be modified in-place, and Walk() will only recurse into the subworkspaces whose names remain in dirnames. This can be used to limit the search, impose a specific order of visiting, or even to inform Walk() about directories the caller creates or renames before it resumes Walk() again. Modifying dirnames when topdown is False is ineffective, because in bottom-up mode the workspaces in dirnames are generated before dirpath itself is generated. (默认值为 True) | Boolean |
onerror | Errors are ignored by default. The onerror function will be called with an OSError instance. The function can be used to report the error and continue with the walk or raise an exception to abort. 注: The file name is available as the filename attribute of the exception object. (默认值为 None) | Function |
followlinks | By default, Walk() does not walk into connection files. Set followlinks to True to visit connection files. (默认值为 False) | Boolean |
datatype | The datatype to limit the results returned. Valid datatypes are:
Multiple datatypes are supported if entered as a list or tuple.
(默认值为 None) | String |
type | Feature and raster data types can be further limited by type.
Valid feature types are:
Valid raster types are:
Multiple datatypes are supported if entered as a list or tuple.
(默认值为 None) | String |
数据类型 | 说明 |
Generator | 提供的三元组包括工作空间、目录名称和文件名称(dirpath、dirnames 和 filenames)。
注: 列表中的名称仅包括基本名称,不包括路径组件。为在 dirpath 中获得文件或目录的完整路径(始于顶级),请运行 os.path.join(dirpath,名称)。 |
代码实例
使用 Walk 函数为面要素类创建目录。
import arcpy
import os
workspace = "c:/data"
feature_classes = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
datatype="FeatureClass",
type="Polygon"):
for filename in filenames:
feature_classes.append(os.path.join(dirpath, filename))
使用 Walk 函数为栅格数据创建目录。将忽略文件夹中所有名为 back_up 的栅格。
import arcpy
import os
workspace = "c:/data"
rasters = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
topdown=True,
datatype="Raster"):
# Disregard any folder named 'back_up' in creating list
# of rasters
if "back_up" in dirnames:
dirnames.remove('back_up')
for filename in filenames:
rasters.append(os.path.join(dirpath, filename))