简体   繁体   中英

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. 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. I"m using Eclipse as my IDE and 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM