What's the best way to open files in use with recursive function

Hi there, I have a script in that I open a file and write some content to it with a recursive function. Normally I open a file with a with-Statement inside the function so after all writing is done the file will be closed automatically.

In this case when I put the with-Statement inside the recursive function it will be opened and closed a lot of times: everytime the function calls itself.

What would you do? Is there some recommendation?

my code:

def go_through_directory(directory):

    file_list = []
    dir_list = []

    with open('README.md', 'a') as f:

        for child in sorted(directory.iterdir()):
            if child.is_file():
            elif child.is_dir():
        for item in file_list:

        for folder in dir_list:

I think about to open the file outside of the function and close it after all work is done.
What is your take about this?

Okay, folks. I did it that way:

def go_through_directory(directory):

   """ Same code as above but without the `write` functionality.
       Moved the `with as`-Statement out of the function and 
       packed the function call in it. """

with open('README.md', 'a') as f:

With that I solved some logical issue as well :slight_smile:

Only thing I see there is don’t you have to pass f to go_through_directory() so it knows what to write too.

Also, this might help:




Then this function is nothing more than:

  1. load template
  2. fill in with directory
  3. apply it
  4. write it

The APIs are pretty easy.

1 Like

Thank you @zedshaw. Awesome. Will have a look in that two templating engines.
Yes, I forgot to add the f to the function. But magically it workes because I have the f in the with statement and in my function. I overlooked that completly.

Voodoo! You should find out why it works.

Yes, I found it out!