简体   繁体   中英

Writing to an .ini file using configparser results in an empty file if restarted while program is running

I have a program that runs a method every five seconds. In this method, I require writing to the configuration .ini file and, because this is embedded software, it must be able to handle the system shutting down at unknown times. However, every time the system shuts down while the program is running, the .ini file is empty when the system starts up again.

Here is the code for the method being run:

def HandleBatteryMonitoring():
    #some code before this...
    systemConfig = ConfigObj('settings.ini')
    systemConfig.filename = 'settings.ini'

    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryMSB)
    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryLSB)
    systemConfig['systemsettings']['batterydischargebusmsb'] = str(dischargeBatteryMSB)
    systemConfig['systemsettings']['batterydischargebuslsb'] = str(dischargeBatteryLSB)
    systemConfig['systemsettings']['batterypercentage'] = str(batteryPercentage)

    systemConfig.write()

Currently it is using ConfigObj, but only because the same problem happened with ConfigParser, and I was hoping a different library would help the problem. Here's the same code when it used ConfigParser:

def HandleBatteryMonitoring():
    #some code before this...
    systemConfig = configparser.ConfigParser('settings.ini')

    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryMSB)
    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryLSB)
    systemConfig['systemsettings']['batterydischargebusmsb'] = str(dischargeBatteryMSB)
    systemConfig['systemsettings']['batterydischargebuslsb'] = str(dischargeBatteryLSB)
    systemConfig['systemsettings']['batterypercentage'] = str(batteryPercentage)

    with open('settings.ini', 'w') as file:
        systemConfig.write(file)

That method is called from here:

def OnHandleCharging():
    while True:
        HandleBatteryCharging()
        time.sleep(5)

It should be noted that, while the program is running, the file is being written to correctly, and I can watch the values changing as the file changes. This only happens when the system is restarted during operation.

I need this config file to not be emptied upon restarting. Any solutions or workarounds for this would be greatly appreciated.

尝试以 'r+' 格式打开文件并更改值,如果您用 'w' 打开文件,它可能会覆盖文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM