使用os.walk()在Python中的递归问题

时间:2014-10-20 03:45:43

标签: python python-2.7 recursion 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

1 个答案:

答案 0 :(得分:3)

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)