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?