Search code examples
pythonfilenewlinewritetofileconfigobj

Writing to an existing file without overwriting/erasing


My goal is quite simple, but I couldn't find it on the guide for configobj. When I run my code I want it to write to a file but not erase what there's in the file already.

I would like everytime I run this it should write underneath what's already in the file

This is my current code: That erase/overwrite what's inside the dasd.ini already

from configobj import ConfigObj

config = ConfigObj()
config.filename = "dasd.ini"
#
config['hey'] = "value1"
config['test'] = "value2"
#
config['another']['them'] = "value4"
#
config.write()

Solution

  • this would be remarkably simpler if configobj accepted a file-like object instead of a file name. This is a solution i offered in comments.

    import tempfile
    with tempfile.NamedTemporaryFile() as t1, tempfile.NamedTemporaryFile() as t2, open('dasd.ini', 'w') as fyle:
        config = ConfigObj()
        config.filename = t1.file.name
        config['hey'] = "value1"
        config['test'] = "value2"
        config['another']['them'] = "value4"
        config.write()
        do_your_thing_with_(t2)
        t1.seek(0)
        t2.seek(0)
        fyle.write(t2.read())
        fyle.write(t1.read())