pythonconfigconfigparser

ConfigParser - Create file if it doesn't exist


So I am working on creating a program in Python that reads a .ini file to set up some boot variables for the main program. My only thing is, I want the program on initialization, to check if the .ini file exists, and if it doesn't, create it with a set of default values. Kind of a preemptive bug fix on if someone accidentally deletes the file.

I can't seem to find any examples anywhere of how to do this, and I'm not super experienced with Python (only been programming with it for about a week) so I'd appreciate any assistance :)

Edit: Upon further thought, I want to pursue this a bit further.

Let's assume the file does exist. How do I check it to make sure it has the appropriate sections? If it doesn't have the appropriate sections, how would I go about deleting the file or removing the contents and rewriting the contents of the file?

I'm trying to idiot proof this :P


Solution

  • You can use ConfigParser and the OS library, here's a quick example:

    #!usr/bin/python
    import configparser, os
    
    config = configparser.ConfigParser()
    
    # Just a small function to write the file
    def write_file():
        config.write(open('config.ini', 'w'))
    
    if not os.path.exists('config.ini'):
        config['testing'] = {'test': '45', 'test2': 'yes'}
    
        write_file()
    else:
        # Read File
        config.read('config.ini')
    
        # Get the list of sections
        print config.sections()
    
        # Print value at test2
        print config.get('testing', 'test2')
    
        # Check if file has section
        try:
            config.get('testing', 'test3')
    
        # If it doesn't i.e. An exception was raised
        except configparser.NoOptionError:
            print "NO OPTION CALLED TEST 3"
    
            # Delete this section, you can also use config.remove_option
            # config.remove_section('testing')
            config.remove_option('testing', 'test2')
    
            write_file()
    

    Output:

    [DEFAULT]
    test = 45
    test2 = yes
    

    Linked above are the docs that are extremely useful to learn more about writing configuration files and other in-built modules.