[我们并不需要os.walk
本身,我们只需要为onerror
参数分配一个参数即可。
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)
[我们并不需要os.walk
本身,我们只需要为onerror
参数分配一个参数即可。