Skip to main content

Walk

Краткая информация

Функция Walk возвращает имена данных в структуре каталог/база данных проходом по дереву сверху вниз или снизу вверх. Каждый каталог/рабочая область дает кортеж из трех составляющих: путь к каталогу, имена каталогов и имена файлов.

Обсуждение

Модуль os содержит функцию os.walk, которую можно использовать для прохода по дереву директорий и поиска данных. Функция os.walk работает только с файлами и не поддерживает работу с содержимым баз данных, например, классов объектов баз геоданных, таблиц и растров. Для лучшей производительности рекомендуется использовать os.walk для файловых форматов. Функцию arcpy.da.Walk можно использовать для создания каталога данных

Синтаксис

Walk(workspace, {topdown}, {onerror}, {followlinks}, {datatype}, {type})

Параметр Объяснение Тип данных

workspace

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. Modifying dirnames when topdown is False is ineffective, because in bottom-up mode, the workspaces in dirnames 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.

  • Any—All data types are returned. This is equivalent to using None or skipping the argument.

  • CadDrawing—CAD files (.dwg, .dxf, and .dgn) are returned.

  • FeatureClass—Feature classes in a geodatabase and shapefiles (.shp) are returned.

  • FeatureDataset—Feature datasets in a geodatabase are returned.

  • GeometricNetwork—Geometric networks in a geodatabase are returned.

  • LasDataset—LAS dataset files (.las and .lasd) are returned.

  • Layer—Layer files (.lyrx) are returned.

  • Locator—Locator files (.loc) are returned.

  • Map— ArcGIS Pro projects (.aprx files), ArcGIS Pro map documents (.mapx files), and ArcMap documents (.mxd files) are returned.

  • MosaicDataset—Mosaic datasets in a geodatabase are returned.

  • NetworkDataset—Network datasets in a geodatabase are returned.

  • ParcelDataset—Parcel fabric datasets are returned.

  • RasterCatalog—Raster catalogs in a geodatabase are returned.

  • RasterDataset—Raster datasets in a geodatabase or in a folder are returned.

  • RelationshipClass—Relationship classes in a geodatabase are returned.

  • RepresentationClass—Representation classes in a geodatabase are returned.

  • Table—Tables in a geodatabase or folder and sheets in Excel workbooks are returned.

  • Terrain—Terrain datasets are returned.

  • Tin—TIN surfaces in a geodatabase are returned.

  • Tool—Tools in a toolbox are returned.

  • Topology—Topologies in a geodatabase are returned.

  • UtilityNetwork—Utility networks in a geodatabase are returned.

Multiple data types are supported if they're entered as a list or tuple.

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
    datatype=['MosaicDataset', 'RasterDataset']):

(Значение по умолчанию — None)

String

type

Specifies whether feature and raster data types will be further limited by type.

  • All—All types are returned. This is equivalent to using None or skipping the argument.

  • Any—All types are returned. This is equivalent to using None or skipping the argument.

Valid feature types are the following:

  • Multipatch—Multipatch feature classes are returned.

  • Multipoint—Multipoint feature classes are returned.

  • Point—Point feature classes are returned.

  • Polygon—Polygon feature classes are returned.

  • Polyline—Polyline feature classes are returned.

Valid raster types are the following:

  • BIL— Esri Band Interleaved by Line file

  • BIP— Esri Band Interleaved by Pixel file

  • BMP— Bitmap graphic raster dataset format

  • BSQ— Esri Band Sequential file

  • DAT— ENVI DAT file

  • GIF— Graphic Interchange Format for raster datasets

  • GRID— Esri Grid raster dataset format

  • IMG— ERDAS IMAGINE raster data format

  • JP2— JPEG 2000 raster dataset format

  • JPG— Joint Photographic Experts Group raster dataset format

  • PNG— Portable Network Graphic raster dataset format

  • TIF— Tag Image File Format for raster datasets

Multiple data types are supported if they're entered as a list or tuple.

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
    datatype='FeatureClass', type=['Polygon', 'Polyline']):

(Значение по умолчанию — None)

String

Возвращаемое значение

Тип данных Объяснение

Generator

Выдает кортеж из трех элементов, который включает рабочую область, имена каталогов и имена файлов.

  • dirpath – путь к рабочей области в виде текстовой строки.

  • dirnames представляет собой список имен подкаталогов и других рабочих областей в dirpath.

  • filenames представляет собой список имен ресурсов, не являющихся рабочими областями, в dirpath.

Примечание:

Имена в этих списках включают только базовое имя; никакие компоненты пути не включаются. Чтобы получить полный путь (начинающийся с вершины) к файлу или директории в dirpath, выполните os.path.join(dirpath, name).

Пример кода

Walk, пример 1

Используйте функцию 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, пример 2

Использует функцию 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))