Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with ConfigParser
#1
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.
Reply
#2
don't use 'a' mode, but 'w', so you will overwrite the existing file
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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?
Reply
#4
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).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ConfigParser(dict_type=) not behaving as expected malonn 5 3,314 Sep-08-2022, 08:42 AM
Last Post: malonn
  using alternate names in configparser Skaperen 6 2,854 Oct-01-2020, 08:27 PM
Last Post: Skaperen
Question configparser.NoSectionError (Python 3.7) alpho 2 5,823 Apr-08-2020, 10:26 PM
Last Post: micseydel
  Error in configparser fullstop 12 9,988 Dec-22-2019, 07:36 PM
Last Post: snippsat
  ConfigParser.NoSectionError: No section: 'Default' degenaro 1 14,473 Jun-08-2018, 08:33 PM
Last Post: ljmetzger
  No module named 'ConfigParser' Bani 13 56,272 May-22-2017, 08:02 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020