0

Trying to go through every folder on a drive, count the number of files in each folder and if the number of files is greater than or equal to 3, increment a count. Should be easy right? Well I've completely borked it and I'm at a loss.

import os, os.path, sys

rootdir = 'q:'

documentedcount = 0

for root, subFolders, files in os.walk(rootdir):
    filecount = len([name for name in os.listdir('.') if os.path.isfile(name)])
    print "Filecount = %s" % filecount
    if  filecount >= 3:
        documentedcount =+1
        print "Documented in the loop is %s" % documentedcount

print "Documented = %s" % documentedcount

It doesn't want to go beyond the root directory and into any of the subfolders. It's driving me nuts because this should be simple as hell but I just can't seem to wrap my head around it.

1
  • Please correct the indentation to match your actual implementation -- it's significant. Commented May 31, 2013 at 19:52

1 Answer 1

2

Well, os.walk() won't change the working directory on each iteration, so the line...

filecount = len([name for name in os.listdir('.') if os.path.isfile(name)])

...will always count the number of files in the current working directory when you started the script.

However, there's a much simpler method, since the third item in each tuple returned by os.walk() already gives you a list of all (non-directory) files in the directory, so you can just use len(files)...

import os, os.path, sys

rootdir = 'q:'

documentedcount = 0

for root, subFolders, files in os.walk(rootdir):
    filecount = len(files)
    print "Filecount = %s" % filecount
    if filecount >= 3:
        documentedcount =+1
        print "Documented in the loop is %s" % documentedcount

print "Documented = %s" % documentedcount
Sign up to request clarification or add additional context in comments.

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.