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
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With