os.walk`的另一种选择只有在访问树中的每个目录时才会抛出StopIteration吗?

问题描述 投票:0回答:1

os.walk返回一个迭代器,该迭代器用于访问某个树中的每个目录。我想要类似os.walk的东西,它会抛出StopIteration(或类似的东西)仅当且仅当>>树中的每个目录都已被访问。 当树中的每个目录都被访问时,

os.walk抛出StopIteration

在执行过程中遇到一些错误。例如,考虑以下打印输出和错误消息:
checking for empty folders under F:\

checking for empty folders under F:\$RECYCLE.BIN

checking for empty folders under F:\$RECYCLE.BIN\S-1-5-18

Traceback (most recent call last):
  File "D:/FILE_MGMT_PYTHON/DRIVER.PY", line 228, in remove_empty_dirs
    directories = next(os.walk(cur))[1]
StopIteration

我的F:\驱动器具有数千个目录和文件。无法全部访问它们。

注意:我没有将F:\设为遍历的根。F:\$RECYCLE.BIN\S-1-5-18是步行的根源。这样,迭代器将永远不会在F:\$RECYCLE.BIN\S-1-5-18以上“向上”移动

起初,我以为F:\$RECYCLE.BIN\S-1-5-18是空的,因此F:\$RECYCLE.BIN\S-1-5-18是在以F:\$RECYCLE.BIN\S-1-5-18为根的树下的last

目录。

但是,next(os.walk(path_to_an_empty_directory))NOT抛出StopIteration

import os
import pathlib
import shutil

if True:
   path = pathlib.Path(os.getcwd()) / "I_am_a_directory"
   if path.is_dir():
       shutil.rmtree(path)
   os.mkdir(path)
   print(next(os.walk(path))[0])
   print("os.walk did not raise ", StopIteration.__name__)

编辑:

我的代码看起来像这样:

import os
import pathlib

def take_a_walk(xpath):

    ipath = pathlib.Path(str(xpath))

    print(''.join(str(x) for x in [
        "VISITED ", str(ipath)
    ]))

    children = next(os.walk(ipath))[1]
    children = [ipath / child for child in children]
    for child in children:
        take_a_walk(child)
    return "Fahrvergnugen"

take_a_walk('F:\\')

os.walk返回一个迭代器,该迭代器用于访问树中的每个目录。我想要像os.walk这样的东西,当且仅当每个...

[我们并不需要os.walk本身,我们只需要为onerror参数分配一个参数即可。

默认情况下,如果在检查路径时遇到错误,则os.walk返回的迭代器将跳过当前路径,并移至下一个路径。

def r(err):
    raise err

os.walk(path, onerror=r)
python python-3.x path filepath hierarchy
1个回答
0
投票

[我们并不需要os.walk本身,我们只需要为onerror参数分配一个参数即可。

© www.soinside.com 2019 - 2024. All rights reserved.