Python Forum
Help with ConfigParser - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help with ConfigParser (/thread-11843.html)



Help with ConfigParser - EricALionsFan - Jul-27-2018

All,

I need some assistance with my Python Code. While I consider myself a intermediate programmer, I tend to struggle with Python code coming from primarily a Visual Basic with Applications background.

import configparser

config = configparser.ConfigParser()

config.read('G:\\WINDOWS\\Gauge_Example.ini')

# Check to see if the section exists
if config.has_section('PROPERTY_ORDER'):
    print('Section exists!')
else:
    config.add_section('PROPERTY_ORDER')
    
    with open(strFile, 'a') as configfile:
        config.write(configfile)
What I am attempting to do is read the INI file and look for a section called 'PROPERTY_ORDER'. If I don't find it, I want to add this section. The way I am doing it now is it wants to append the entire contents of the file (again) plus my added section, which I do not want.

I am sure this is something simple that I am missing, but if someone could point me in the right direction, I think I may get it from there.


RE: Help with ConfigParser - buran - Jul-27-2018

don't use 'a' mode, but 'w', so you will overwrite the existing file


RE: Help with ConfigParser - EricALionsFan - Jul-27-2018

So, just for my own knowledge, there is no way to just append the section to the end of the INI file without overwriting it?


RE: Help with ConfigParser - buran - Jul-27-2018

Not with ConfigParser method. Frankly I don't see the point.
Of course you can always open/append to the end of the ini file as it is plain txt file (as long as you know the format and are able to replicate it).