Reputation: 31
my program is
import os
from traceback import format_exc
import pdb
des="testdir"
def generate_cabfile(folder):
for parent,dirs, files in os.walk(folder):
print parent
print dirs
print files
print "-----------------"
for file in files:
file_path = os.path.join(parent, file)
for dir in dirs:
chile_folder = os.path.join(parent, dir)
generate_cabfile(chile_folder)
print "this is over"
generate_cabfile(des)
my dir tree is
testdir/1.txt
testdir/2.txt
testdir/mu/a.txt
the output is very strange,which has two dir 'mu' output:
testdir
['mu']
['1.txt', '2.txt']
-----------------
testdir/mu
[]
['a.txt']
-----------------
this is over
testdir/mu
[]
['a.txt']
-----------------
this is over
Upvotes: 0
Views: 33
Reputation: 387557
os.walk
already visits all subdirectories it encounters (that’s why it’s called “walk”; it walks through the whole directory structure). So you do not need to recursively call your function again for every directory you see.
Your logic would be appropriate if you were using os.listdir
to just give you the contents of a single directory. In that case, you would have to recursively list the contents for every subdirectory too.
Upvotes: 1