I found several questions on this topic, but none of them addressed the problem that I see. I apologize in advance, I'm new to python. What I'm trying to do is count the number of files in each directory under somedir / to get something like:
dir-a: 13 dir-b: 6 dir-c: 21
I thought the easiest way to prove that I could do this:
from os import listdir from os.path import isfile, isdir def walk(p): for file in listdir(p): if isfile(file): print("File: " + file) elif isdir(file): print("Dir: " + file) walk(file) else: print("Unknown: " + file) path = raw_input('Enter path to search') walk(path)
But the first iteration is the only one that works as expected. I tried adding the full path to the file using os.path.abspath and a couple of other ways to ensure that the file is the same in the first iteration as in the recursive calls. I checked the type with type(file) and it is 'str' , and even if the path + file name is correct and exists, the above program frames do not give the expected results. For example, in a directory structure, for example:
dir-a/ file-a.1 file-a.2 dir-b/ file-b.1 file-b.2 file-a.3
I would expect:
File: file-a.1 File: file-a.2 Dir: dir-b File: file-b.1 File: file-b.2 File: file-a.3
but I get:
File: file-a.1 File: file-a.2 Dir: dir-b Unknown: file-b.1 Unknown: file-b.2 File: file-a.3
Thus, basically all files are not recognized as files or channels in recursive calls. I looked through the documents on listdir , isfile and isdir , and that still doesn't make sense. I tried with python 2.7.5 and 3.4.0, the same behavior. Any help is appreciated.
source share