Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read ini file
#1
Hi,

When running the below code, I get an error message but I don't understand it. I appreciate some insights.
TIA

data.ini
[settings]
volume = "99"
tz = "2"
first-1 = "a"
first-2 = "b"
first-3 = "c"
readini.py
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser  # ver. < 3.0

# instantiate
config = ConfigParser()

# parse existing file
config.read('data.ini')

def readInstance(instance):
    if instance in config.sections(): #checks if the given instance actually exists in the config file
        volume = config.getint[instance]["volume"].strip('\"') #read the specific config data and then convert it into an integer
        tz = config.getint[instance]["tz"].strip('\"') # repeat process for ending
        print volume
        print tz

readInstance("settings")
#print config.getint('settings', 'volume').strip('\"')
error msg.
Traceback (most recent call last):
  File "readini.py", line 24, in <module>
    readInstance("settings")
  File "readini.py", line 14, in readInstance
    volume = config.getint[instance]["volume"].strip('\"') #read the specific config data and then convert it into an integer
TypeError: 'instancemethod' object has no attribute '__getitem__'
Reply
#2
Hello,
I am not very familiar with the module, but after quickly glancing the examples in docs, you may not be using getint() right
example:
an_int = config.getint('Section1', 'an_int')
Reply
#3
Thank you. modified the code but getting a different error. I guess I'm not able to strip the '"'

try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser  # ver. < 3.0

# instantiate
config = ConfigParser()

# parse existing file
config.read('data.ini')

def readInstance(instance):
    if instance in config.sections(): #checks if the given instance actually exists in the config file
        #read the specific config data and then convert it into an integer        
        volume = config.getint(instance,'volume').strip('\"')
        # repeat process for ending
        tz = config.getint(instance,'tz').strip('\"') # repeat process for ending
        print volume
        print tz

readInstance("settings")
#print config.getint('settings', 'volume').strip('\"')
error:
Traceback (most recent call last):
  File "readini.py", line 27, in <module>
    readInstance("settings")
  File "readini.py", line 15, in readInstance
    volume = config.getint(instance,'volume')
  File "/home/pi/.local/lib/python2.7/site-packages/backports/configparser/__init__.py", line 834, in getint
    return self._get_conv(section, option, int, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/backports/configparser/__init__.py", line 822, in _get_conv
    return self._get(section, conv, option, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/backports/configparser/__init__.py", line 814, in _get
    return conv(self.get(section, option, **kwargs))
ValueError: invalid literal for int() with base 10: '"99"'

Solved using config.get instead of config.getint.
Reply
#4
config.get will probably determine the data type automatically, which could sometime have undesirable effects.
If you want to strictly enforce getting an integer value, using getint would be a better choice.
The problem in this case is in the data.ini file.
volume = "99"
# should be
volume = 99
Reply
#5
your file should look like this
Output:
[settings] volume = 99 tz = 2 first-1 = a first-2 = b first-3 = c
then
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser  # ver. < 3.0
 
# instantiate
config = ConfigParser()
 
# parse existing file
config.read('data.ini')
 
def readInstance(instance):
    if instance in config.sections(): #checks if the given instance actually exists in the config file
        #read the specific config data and then convert it into an integer        
        volume = config.getint(instance,'volume')
        # repeat process for ending
        tz = config.getint(instance,'tz') # repeat process for ending
    return (volume, tz)

vol, tz = readInstance("settings")
print('volume: --> type: {} --> value: {}'.format(type(vol), vol))
print('tz: --> type: {} --> value: {}'.format(type(tz), tz))
Output:
volume: --> type: <type 'int'> --> value: 99 tz: --> type: <type 'int'> --> value: 2 >>>
I personally would do it a bit differently - i.e. with try/except and printing message if section/option is missing, or using get and supply default value like None
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
#6
Thank you but unfortunately, I don’t have control over the ini file which is generated by a web form through a php code. Nor I have a monitor to see the output since I’m running the code on a headless Raspberry PI.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Recommended way to read/create PDF file? Winfried 3 2,886 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,446 Nov-09-2023, 10:56 AM
Last Post: mg24
  read file txt on my pc to telegram bot api Tupa 0 1,117 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,110 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,281 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 6,585 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Read csv file with inconsistent delimiter gracenz 2 1,200 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Read text file, modify it then write back Pavel_47 5 1,592 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  Correctly read a malformed CSV file data klllmmm 2 1,941 Jan-25-2023, 04:12 PM
Last Post: klllmmm
  How to read csv file update matplotlib column chart regularly SamLiu 2 1,061 Jan-21-2023, 11:33 PM
Last Post: SamLiu

Forum Jump:

User Panel Messages

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