It’s nice to close your file descriptors, but most of the time it’s not a requirement, OS will do it for you upon the process exit.
The problem here is that you use two different approaches at the same time, and they conflict, leaving you in an unconsistent state, which happens to manifest as an empty file in your case, but seems to me as an undefined behaviour in general.
Let’s inspect your code in English, much simplified:
- Open a file named “a.json”, and have its instance in a variable named
- Construct a string, and write it out to a file that we have open in a variable
- Open a file named “a.json”, and write to it the contents of a variable
Just remove the last line and your problem should go away, but keep
, "w" bit.