I’ve run into this issue myself! The ‘w’ mode is the culprit here because it literally means ‘write (and wipe),’ so it clears the file each time. If you want to add to the file without overwriting, you’ll need to use ‘a’ mode. It’s perfect when you’re appending from multiple functions. Here’s a simple example:
with open("output.txt", "a") as f:
f.write("This will be added to the end of the file.\n")
I rely on this method a lot, especially when logging from recursive or async functions. It’s really reliable and saves a lot of hassle.