I haven't read your entire block of code yet, but I do have one piece of advice already - explore opening your file using the append mode ('>>') instead. This will address your concern about adding "new key/value pairs to the end of the file without disturbing the comments or the empty lines".
---
It's all fine and dandy until someone has to look at the code.