简体   繁体   中英

ConfigParser: Every time I start program, config file was overwritten - Python

I'm learning some of Python and I have one question that I can't fix. But first of all I will tell what I want:

  1. When program start, if config file not exist, create a new ones ("template config"). Otherwise don't do nothing (software later will load the config file).
  2. When user change something, config file need be modified.
  3. When user exit software, config file must keep intact.

Well, the second and the thirt steps I already done, because they're almost the same. My problem is with the first step. Now my software create a new config file if not exist, but if the file already exist (with configs) my app overwrite this "old" file and generate my "template config".

I want know how I can fix that to my software DON'T overwrite the file if this already exist.

Following is my code:

def generate_config_file(self, list):

        config = ConfigParser()
        for index, item in enumerate(list):
            config.add_section(str(index))
            config.set(str(index), 'id', 'idtest')
            config.set(str(index), 'name', 'nametest')

        # Creating the folder
        myFolder = "/etc/elementary/"
        if not os.path.exists(myFolder):
            os.makedirs(myFolder)

            # Creating the file
            filePath = "/etc/elementary/settings.cfg"
            with open(filePath, 'wb') as configfile:
                config.write(configfile)

    return

What can I do to solve my problem?

You are only checking if the folder exists. You need to also check if the file itself exists, and only create it if it doesn't exist.

filePath = "/etc/elementary/settings.cfg"
if not os.path.exists(filePath):
    with open(filePath, 'wb') as configfile:
        config.write(configfile)

Alternatively, use os.path.exists to check for the file's existence before you call your function in the first place.

You just need check if the file exists before calling your function:

if not os.path.exists("/etc/elementary/settings.cfg"):
     obj.generate_config_file(...)

or add this to the top of your function:

def generate_config_file(self, list): 
    if os.path.exists("/etc/elementary/settings.cfg"):
        return
    ...

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