Python ConfigParser - create file if it doesn't exist

So I am working on making a Python program that reads an .ini file to set up some boot variables for the main program. My only one, I want the program to initialize to check if the .ini file exists, and if not, create it with a set of defaults. The kind of fix is ​​fixed if someone accidentally deletes a file.

I can't seem to find any examples of how to do this, and I'm not very experienced with Python (only programming with it for about a week), so I would be grateful for any help :)

EDIT: Next think, I want to continue this a bit.

Let's assume the file exists. How do I check it to make sure it has the appropriate sections? If it doesn't have matching sections, how do I manage to delete the file or delete the contents and overwrite the contents of the file?

I'm trying to prove it with an idiot: P

+3


source to share


1 answer


You can use ConfigParser and OS , 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

      

The linked are documents that are extremely useful to learn more about writing configuration files and other builtins.

Note . I'm a bit new to python, so if anyone knows a better approach, let me know, I'll edit my answer!

+5


source







All Articles