摘要
通过从上至下或从下至上遍历树,返回目录和数据库结构中的数据名。 每个目录或工作空间将生成一个三元组:目录路径、目录名称和文件名称。
说明
os 模块包括 os.walk 函数,可用于遍历目录树并查找数据。 os.walk 函数基于文件,不识别地理数据要素类、表或栅格等数据库内容。 为了获得更好的性能,建议您将 os.walk 用于基于文件的格式。 arcpy.da.Walk 函数可用于为数据创建目录。
语法
Walk (top, {topdown}, {onerror}, {followlinks}, {datatype}, {type})
参数 | 说明 | 数据类型 |
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 trom the top down). If topdown is False, the tuple for a workspace is generated after the tuple for all of its subworkspaces (workspaces are generated from the 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 inform Walk about directories the caller creates or renames before it resumes Walk again. Modifyingdirnames when topdown is False is ineffective, because in bottom-up mode, the workspaces indirnames are generated before dirpath is generated. (默认值为 True) | Boolean |
onerror | Errors are ignored by default. The onerror function will be called with an OSError instance. This function can be used to report the error and continue with Walk or raise an exception to cancel. 注:The file name is available as the filename attribute of the exception object. (默认值为 None) | Function |
followlinks | By default, Walk does not visit connection files. Set followlinks to True to visit connection files. (默认值为 False) | Boolean |
datatype | Specifies the data type that will be used to limit the results.
Multiple data types are supported if they're entered as a list or tuple.
(默认值为 None) | String |
type | Specifies whether feature and raster data types will be further limited by type.
Valid feature types are the following:
Valid raster types are the following:
Multiple data types are supported if they're entered as a list or tuple.
(默认值为 None) | String |
数据类型 | 说明 |
Generator | 提供的三元组包括:工作空间、目录名称和文件名称。
注:列表中的名称仅包括基本名称,不包括路径组件。 要获得 dirpath 中的文件或目录的完整路径(从顶部开始),请使用 os.path.join(dirpath, name)。 |
代码示例
使用 Walk 函数为面要素类在工作空间中创建目录。
代码将包含文件地理数据库中任何要素数据集中的面要素类。
import arcpy
import os
workspace = "c:/data"
feature_classes = []
walk = arcpy.da.Walk(workspace, datatype="FeatureClass", type="Polygon")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
feature_classes.append(os.path.join(dirpath, filename))
使用 Walk 函数为栅格数据创建目录。 将忽略名为 back_up 的文件夹中的所有栅格。
import arcpy
import os
workspace = "c:/data"
rasters = []
walk = arcpy.da.Walk(workspace, topdown=True, datatype="RasterDataset")
for dirpath, dirnames, filenames in walk:
# 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))