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:
        f.write(f"{directory.name}\n\n")

        for child in sorted(directory.iterdir()):
            if child.is_file():
                file_list.append(child)
            elif child.is_dir():
                dir_list.append(child)
        
        for item in file_list:
            f.write(f"{item.name}\n\n")

        for folder in dir_list:
            go_through_directory(folder)

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:
    go_through_directory(docs)

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:

http://jinja.pocoo.org/

or

https://www.makotemplates.org/

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!