0

Why does this recursive function keep returning multiple dictionaries instead of just one.

def retFiles(dir):
    data = {}
    root = set()
    os.chdir(dir)
    cwd = os.getcwd()
    for i in os.listdir(cwd):
        if os.path.isfile(i):
            data.setdefault(i, set())
            root.add(os.path.relpath(dir).replace("\\", "/"))
            data[i] = root
        else:
            preisci(i)
    print(data)
2
  • 10
    Uh... that function doesn't return ANYTHING... Commented Dec 18, 2011 at 5:40
  • Is the last line (print(data)) supposed to represent what would typically be returned from the method? Commented Dec 18, 2011 at 5:43

3 Answers 3

2

There are two problems:

  1. Your function isn't recursive (unless preisci calls retFiles, but you haven't shown that code).
  2. It doesn't return anything, let alone multiple dictionaries as you claim.

I wouldn't actually use recursion here. Instead consider using the os.walk function that can recursively walk down a directory and all its subdirectories.

To fix the second point, try changing the print to a return statement.

Sign up to request clarification or add additional context in comments.

Comments

1

Actually it makes sense why the method would return a list of lists (if the print(data) line is actually supposed to be the return).

    if os.path.isfile(i):
        data.setdefault(i, set())
        root.add(os.path.relpath(dir).replace("\\", "/"))
        data[i] = root
    else:
        preisci(i)

The line

data[i] = root

is assigning a list of paths to the i'th index of data. So if we are supposed to be returning data then data will contain multiple lists of paths.

Comments

0

You have the print in every function call. So it will print every time this function is run, which is multiple times if the function runs itself recursively. And yes, this function isn't recursive, but my guess is that you intended to type something like

else:
        retFiles(i)

in your implementation. That still wouldn't work the way you likely want it to, but that would be the recursion I think you might be referring to. And then you'd have multiple prints happen.

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.