I have a config.ini file like this:
[LABEL]
NAME = "eventName"
And I am reading it into my python code as shown below. However, when I compare it with the exactly the same string, the result is False
. I wonder if I should use a different way to read this or I need to do something else?
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
my_label_name = config['LABEL']['name']
print("My label is: ", my_label_name, " and has type of: ", type(my_label_name))
My label is: "eventName" and has type of: <class 'str'>
print(my_label_name == "eventName")
False
CodePudding user response:
By default, the config parser reads the content from your config file as string. In the config file, single and double quotes are not required to represent a string. The quotes will be considered as a separate character itself.
In your program, if you observe properly, you can see the value is getting printed with the quotes. So eventName and "eventName" are not the same. This is the reason you are getting False as the result. The screenshot of your program is given below.
So the solution is remove double quotes from your config file or remove double quotes at the time of reading the value.
The updated config file is given below.
[LABEL]
NAME = eventName
If you cannot remove double quotes from the config file, you need to handle it in the program. The sample code snippet is given below.
import ast
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# Modify here
#my_label_name = config['LABEL']['name']
my_label_name = ast.literal_eval(config['LABEL']['name'])
print("My label is: ", my_label_name, " and has type of: ", type(my_label_name))
print(my_label_name == "eventName")
CodePudding user response:
I guess you should change this line:
my_label_name = config['LABEL']['name']
to this:
my_label_name = ast.literal_eval(config['LABEL']['name'])
CodePudding user response:
The contents of config['LABEL']['name']
is a str containing "eventName"
with the double quotes.
Single ('
) and double ("
) quotes are unnecessary in INI where everything is a string.
Demo:
from io import StringIO
import configparser
raw_config = """\
[LABEL]
NAME = "eventName"
"""
with StringIO(raw_config) as buf:
config = configparser.ConfigParser()
config.read_file(buf)
print(config["LABEL"]["NAME"]) # "eventName"