簡體   English   中英

使用os.walk()的Python中的遞歸問題

[英]Recursive problems in Python using os.walk()

我對使用Python(強C#背景)非常陌生,因此我仍在學習應該從函數中獲得什么結果。 我得到一個創建遞歸函數的怪異結果,該函數將借用目錄結構。 我正在使用os.walk()函數,在我看來,一旦您借用了足夠多的內容,查找空文件夾時就不會清除“目錄”的返回結果。 我正在使用Eclipse作為我的IDE和Python 2.7

def CheckSubFolder( folder ):

    print "Checking folders in : " + folder;

    for (root, directories, files) in os.walk(folder):
        for folder2 in directories:
            print folder2;

        for folder2 in directories:
            CheckSubFolder( folder + "\\" + folder2);

    return;

# Code Entry
InFolder = sys.argv[1];
CheckSubFolder( InFolder );
sys.exit(); 

這是我正在使用的示例目錄結構。

State
    -> 1
        -> 2
        -> 3
            -> 4
            -> 5
                -> 6
                -> 7

這是我返回的結果:

Checking folders in : \\State
1
Checking folders in : \\State\1
2
3
Checking folders in : \\State\1\2
Checking folders in : \\State\1\3
4
5
Checking folders in : \\State\1\3\4
Checking folders in : \\State\1\3\5
6
7
Checking folders in : \\State\1\3\5\6
Checking folders in : \\State\1\3\5\7
6
7
Checking folders in : \\State\1\3\6
Checking folders in : \\State\1\3\7
4
5
Checking folders in : \\State\1\4
Checking folders in : \\State\1\5
6
7
Checking folders in : \\State\1\6
Checking folders in : \\State\1\7

os.walk本身是遞歸的。 不要遞歸地調用它:

def CheckSubFolder( folder ):
    for root, directories, files in os.walk(folder):
        for d in directories:
            print "folder : " os.path.join(root, d)
        for f in files:
            print "file   : " os.path.join(root, f)

# Code Entry
path = sys.argv[1]
CheckSubFolder(path)

暫無
暫無

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

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