Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 473
Skitzafreak Avatar asked Jul 04 '17 13:07

Skitzafreak


People also ask

What is Configparser Configparser ()?

Source code: Lib/configparser.py. This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files.

How do you write an INI file in Python?

Python File: # Read file and and create if it not exists config = iniFile( 'FILE. INI' ) # Get "default_path" config. default_path # Print (string)/path/name print config. default_path # Create or Update config.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.


1 Answers

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.

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

like image 196
mrhallak Avatar answered Sep 28 '22 08:09

mrhallak