簡體   English   中英

搜索子目錄python

[英]Search for sub-directory 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

curDir是正在搜索的當前目錄,下一行輸出是子目錄列表。 程序找到沒有子目錄的目錄后,它將跳回到上一級並轉到下一個目錄。

如果需要,我可以提供我的代碼,但不想一開始就發布它,以免產生更大的文本牆。

我的問題是:為什么腳本在搜索了幾個文件夾后就放棄了? 在此先感謝您的幫助!

每當迭代器沒有更多值可生成時,就會引發StopIteration

為什么使用os.walk(dir).next()[1] 僅在for循環中執行所有操作會更容易嗎? 喜歡:

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

這是os.walk的文檔。

對我有用的是在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)將在Parent / Folder / Mydir中查找。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM