You cannot easily write part of a file - in the end, you will rewrite the entire file. If you write a partial file, you will need to search for the starting position, crop the file to this length (or crop, then search / add), and then write a new file tail after an unchanged start. File systems do not support operations such as "delete 329 bytes at offset 193 and insert 46 bytes after the resulting offset 227".
If your YAML module (library) saves or makes available leading comments and blank lines in some way, then you can easily save them. If not, then you probably have to do the work yourself - read and save the comment lines, then use YAML to parse the file, then write the saved comments and the replacement YAML.
source
share