2

I'm working on a script that will crawl a hard drive and collect information on each file it encounters by way of fnmatch and magic.

I have a feeling that the first nested for-loop in yield_files(root) are unnecessary

def yield_files(root):
    
    for root, dirs, files in os.walk(root):
        """ Is this necessary 

        for directory in dirs:
            for filename in directory:
                filename = os.path.join(root, filename)
                if os.path.isfile(filename) or os.path.isdir(filename):
                    yield FileInfo(filename)
        """

        for filename in files:
            filename = os.path.join(root, filename)
            if os.path.isfile(filename) or os.path.isdir(filename):            
                yield FileInfo(filename)
                    

Would os.walk() end-up recursing into these directories anyway?

1 Answer 1

7
def yield_files(root):
    for root, dirs, files in os.walk(root):
        for filename in files:
            filename = os.path.join(root, filename)
            if os.path.isfile(filename) or os.path.isdir(filename):            
                yield FileInfo(filename)

That's all you need. The rest is indeed unnecessary. os.walk goes into subdirectories so you don't need the current directory's path, you just need root as the base for the path join as you've done.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.