0

Why is this recursive function returning more than 1 dictionary aka printing them each time it cycles why isn't it adding new findings to the existing dictionary.

And no i dont want to use os.walk and yes i am aware theres no return

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:
            retFiles(i)
    print(data)
Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
Sterling Duchess
  • 1,970
  • 16
  • 51
  • 91

3 Answers3

3

You're creating a new dictionary with each call to retfiles() when you set data = {}. Therefore it can't append to the data dictionary in the caller's scope.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
3

Your solution has several problems:

1) The recursive call changes the directory during the loop: Remaining files/directories will not be found any more (because folder was switched). SOLUTION: Use complete path to address files and do not change current directory (os.path.join is your friend here)

2) Like already told by e-satis and tim, the dict you are manipulating is a new one for every recursive call and you have to either return the dict or pass it as argument.

And I think your problem has still other reasoning errors. What exactly do you want to achieve with your function please?

gecco
  • 17,969
  • 11
  • 51
  • 68
2

Either pass your dictionnary as a parameter to keep the reference to the same dictionary, or use return to use the dictionary resulting of the previous call.

Either ways, your recursive function, as all recursive calls, need to work on the same data, otherwise it's useless.

Bite code
  • 578,959
  • 113
  • 301
  • 329
  • So i just add a return statement at the end of the function ? – Sterling Duchess Dec 18 '11 at 12:10
  • Yes, and you must use the return result to incorporate in into the previous dict – Bite code Dec 18 '11 at 12:15
  • I did that however if i run that function then on a given folder it will only return 1 finding i have return data at the end of the function and all works well but it returns only 1 file – Sterling Duchess Dec 18 '11 at 12:20
  • First, we don't have cristal balls, so if you want answers, you need to provide outputs. Second, if you remove the code from the question, you are not helping. Eventually, you probably don't even need recursion at all, and seems you are a beginer, you should try with something simpler. Recursion is hard. – Bite code Dec 18 '11 at 15:06