搜索子目录python

wnn*_*maw 3 python

我正在尝试自动指定我的脚本之一所需的子目录。这个想法是让脚本在 C: 驱动器中搜索特定名称的文件夹。在我看来,这需要递归搜索功能。计划是检查所有子目录,如果没有一个是所需的目录,则开始搜索当前子目录的子目录

在研究如何做到这一点时,我遇到了这个问题并开始使用os.walk(dir).next()[1]列出目录。这取得了有限的成功。当脚本搜索目录时,它基本上会放弃并中断,从而给出错误StopIteration。下面的示例输出在 中搜索子目录TEST1

C:\Python27>test.py
curDir:  C:\Python27
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'pyinstaller-2.0', 'Scripts', 'tcl', 'TEST1',     'Tools']
curDir:  DLLs
[]
curDir:  Doc
[]
curDir:  include
[]
curDir:  Lib
['bsddb', 'compiler', 'ctypes', 'curses', 'distutils', 'email', 'encodings', 'hotshot',     
'idlelib', 'importlib', 'json', 'lib-tk', 'lib2to3', 'logging', 'msilib', 
'multiprocessing', 'pydoc_data', 'site-packages', 'sqlite3', 'test', 'unittest', 'wsgiref', 'xml']
curDir:  bsddb
Traceback (most recent call last):
  File "C:\Python27\test.py", line 24, in <module>
    if __name__ == "__main__": main()
  File "C:\Python27\test.py", line 21, in main
    path = searcher(os.getcwd())
  File "C:\Python27\test.py", line 17, in searcher
    path = searcher(entry)
  File "C:\Python27\test.py", line 17, in searcher
    path = searcher(entry)
  File "C:\Python27\test.py", line 6, in searcher
    dirList = os.walk(dir).next()[1]
StopIteration
Run Code Online (Sandbox Code Playgroud)

curDir是正在搜索的当前目录,输出的下一行是子目录列表。一旦程序找到没有子目录的目录,它就会返回一级并转到下一个目录。

如果需要,我可以提供我的代码,但不想最初发布它以避免更大的文本墙。

我的问题是:为什么脚本在搜索了几个文件夹后就放弃了?在此先感谢您的帮助!

mr2*_*ert 5

StopIteration每当迭代器没有更多值要生成时就会引发。

你为什么使用os.walk(dir).next()[1]?在 for 循环中完成所有操作不是更容易吗?喜欢:

for root, dirs, files in os.walk(mydir):
    #dirs here should be equivalent to dirList
Run Code Online (Sandbox Code Playgroud)

这是 的文档os.walk