0

I've got a python script that deletes an entire directory and its subfolders, and I'd like to print out the number of files and folders removed. Currently, I have found some code from a different question posed 2010, but the answer I receive back is 16... If I right-click on the the folder it states that theres 152 files, 72 folders...

The code I currently have for checking the directory;

import os, getpass

user = getpass.getuser()
copyof = 'Copy of ' + user
directory = "C:/Documents and Settings/" + user
print len([item for item in os.listdir(directory)])

How can I extend this to show the same number of files and folders that there actually are?

1
  • this python script doesn't count files which are contained in subfolders. Thus you see discrepancy in numbers Commented Apr 20, 2015 at 17:27

2 Answers 2

3

To perform recursive search you may use os.walk.

os.walk(top, topdown=True, onerror=None, followlinks=False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Sample usage:

import os
dir_count = 0
file_count = 0
for _, dirs, files in os.walk(dir_to_list_recursively):
    dir_count += len(dirs)
    file_count += len(files) 
Sign up to request clarification or add additional context in comments.

3 Comments

Using this script, and adding in the directory, I get; valueError: too many values to unpack
Ugh, my bad, quoted good function from documentation, used bad in example.
I've got a bit of it working... I can now successfully count the number of files in a directory and its subdirectories, but how can I expand this to take into account folders? pastebin.com/b70vWUqB
0

I was able to solve this issue by using the following code by octoback (copied directly);

import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])

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.