2013-08-06 84 views
2

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

在研究如何做到这一点时,我遇到了this question并开始使用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 

curDir是正在搜索的当前目录和输出的下一行是子目录列表。一旦程序找到一个没有子目录的目录,它就开始备份一个级别并进入下一个目录。

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

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

回答

3

StopIteration在迭代器没有更多值生成时会引发。

为什么使用os.walk(dir).next()[1]?在for循环中做所有事情不是更容易吗?像:

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

这是的文档。

+0

是的,这很容易,辉煌!谢谢! – wnnmaw

+0

@wnnmaw我添加了一个到'os.walk'文档的链接。这是一个非常强大的命令。 – mr2ert

+0

使用for循环完美,但非常缓慢。通过600 GB的驱动器搜索大约需要10分钟。有没有更快的方法来调用os.walk,或者更快的替代命令? – wnnmaw

1

什么工作对我来说是指定在os.walk的完整路径,而不仅仅是目录名称:

# fullpath of the directory of interest with subfolders to be iterated (Mydir) 
fullpath = os.path.join(os.path.dirname(__file__),'Mydir') 

# iteration 
subfolders = os.walk(fullpath).next()[1] 

这发生在我身上特别是当包含os.walk一个模块位于子文件夹本身,由父文件夹中的脚本导入。

Parent/ 
    script 
    Folder/ 
     module 
     Mydir/ 
      Subfolder1 
      Subfolder2 

在脚本中,os.walk('Mydir')将在Parent/Mydir中查找,该不存在。

另一方面,os.walk(fullpath)将在父/文件夹/ Mydir中查找。