2

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(".", "")
3
  • I just tested it on ubuntu 12.04 with python 2.7 and it worked. Not sure why its not for you. Commented Feb 7, 2013 at 23:15
  • @placeybordeaux im on os x... could this be a problem? Commented Feb 7, 2013 at 23:22
  • 1
    As a side note: Don't put parentheses around if conditions and the like in Python; it's jarring and draws the attention to "Is he doing something complex here that needs parentheses?" instead of the actual condition. Commented Feb 7, 2013 at 23:47

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the answer, I was unaware of os walk, but it seems quite simple to implement.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.