0

I wish I could explain my problem better, but I simply don't know why my code is not working. I suspect it has to do with scoping, but my searches haven't availed me of a clear solution. I'm generally a Javascript/Java programmer, so perhaps you can understand my confusion.

def ls(directory, times=None):
    if times is None:
        times = 0
    for root, dirs, files in os.walk(directory):
        for dirname in dirs:
            print('    ' * times + dirname)
            ls(dirname, times + 1)
        for filename in files:
            print('    ' * times + filename)

Which should ideally print any given directory structure like so:

a
    b
        c
    d
    e

However, the space indents aren't included because for some reason, subsequent recursive calls to ls() show that the variable times is reset to 0 in the for loop for os.walk(directory). Why is that variable being "reset"?

Dennis
  • 597
  • 4
  • 8
  • 24
  • 1
    What is `ls_walk`? – chash May 13 '20 at 18:50
  • typo. Let me edit that. – Dennis May 13 '20 at 18:50
  • `os.walk` is already recursive, so it doesn't make any sense to write another recursive function on top of it. If you need to write a recursive function and reinvent the `os.walk` wheel, probably for a homework assignment, try `os.listdir` and recurse on every directory that yields. – ggorlen May 13 '20 at 18:54
  • I'm a little confused, because `os.walk` is already providing the recursive walk. What you need to know is the depth at any given iteration, which you can figure out by comparing `root` with `directory`. – chash May 13 '20 at 18:54
  • I'm less interested in solving the problem of printing the directory structure than I am in figuring out what's happening to the variable. – Dennis May 13 '20 at 19:07
  • 1
    @Dennis Your recursive call attempts to walk a non-existent directory (`dirname` instead of `os.path.join(root, dirname)`), so nothing is ever printed where `times != 0`. `os.walk` hides the error by default. – chash May 13 '20 at 19:36
  • This is not even an issue related to the variable. The whole point is just that `os.walk`. – Sraw May 13 '20 at 19:38
  • @hmm You are right. Mark solved or close? – Dennis May 13 '20 at 19:47
  • Close? There are already a lot of posts about how os.walk works. – chash May 13 '20 at 19:54

0 Answers0