kekkles4
kekkles4

Reputation: 111

python directory recursive traversal program

my program does not believe that folders are directory, assuming theyre files, and because of this, the recursion prints the folders as files, then since there are no folders waiting to be traversed through, the program finishes.

import os
import sys
class DRT:
    def dirTrav(self, dir, buff):
        newdir = []
        for file in os.listdir(dir):
            print(file)
            if(os.path.isdir(file)):
                newdir.append(os.path.join(dir, file))
        for f in newdir:
            print("dir: " + f)
            self.dirTrav(f, "")
dr = DRT()
dr.dirTrav(".", "")

Upvotes: 2

Views: 2304

Answers (2)

abarnert
abarnert

Reputation: 365717

The problem is that you're not checking the right thing. file is just the filename, not the pathname. That's why you need os.path.join(dir, file), on the next line, right? So you need it in the isdir call, too. But you're just passing file.

So, instead of asking "is .foo/bar/baz a directory?" you're just asking "is baz a directory?" It interprets just baz as ./baz, as you'd expect. And, since there (probably) is no "./baz", you get back False.

So, change this:

if(os.path.isdir(file)):
    newdir.append(os.path.join(dir, file))

to:

path = os.path.join(dir, file)
if os.path.isdir(path):
    newdir.append(path)

All that being said, using os.walk as sotapme suggested is simpler than trying to build it yourself.

Upvotes: 2

sotapme
sotapme

Reputation: 4903

See os.walk from there:

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

Upvotes: 7

Related Questions