简体   繁体   English

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

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

I'm very new to using Python (strong c# background), so I'm still learning what results I should expect from functions. 我对使用Python(强C#背景)非常陌生,因此我仍在学习应该从函数中获得什么结果。 I'm getting weird results creating a recursive function which will borrow down a directory structure. 我得到一个创建递归函数的怪异结果,该函数将借用目录结构。 I'm using the os.walk() function and it appears to me that once you borrow deep enough, the return results for the 'directories' aren't been cleared when finding an empty folder. 我正在使用os.walk()函数,在我看来,一旦您借用了足够多的内容,查找空文件夹时就不会清除“目录”的返回结果。 I"m using Eclipse as my IDE and Python 2.7 我正在使用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(); 

Here is the example directory structure that I'm using. 这是我正在使用的示例目录结构。

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

Here are the results that I'm being return: 这是我返回的结果:

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 itself works recursively. os.walk本身是递归的。 Don't call it recursively: 不要递归地调用它:

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