I have a configuration file (abc.ini)as below
[DEFAULTS]
plus = plus.jpg
[PATHS]
folderPath = None
import configparser
config = configparser.ConfigParser()
config.read("abc.ini", encoding="utf-8")
print(config.sections()) # works ok
config["PATHS"].folder_path = path # path is some path
I don't understand whats happening in config["PATHS"].folder_path = path
when I do config["PATHS"]["folder_path"] I am getting an error.
Also, to access a value, we can use config["PATHS"]["folderPath"]
but can't we use config["PATHS"].folderPath
dear Larz60+
thanks for the reply
when i use config ["PATHS"]["folder_path"] i get error
you have extra [
at the end of PATHS
(Dec-21-2019, 08:26 AM)buran Wrote: [ -> ]you have extra [
at the end of PATHS
thanks, but that was just a typo.
Even when I fix it I am getting the error
(Dec-21-2019, 08:29 AM)fullstop Wrote: [ -> ]Even when I fix it I am getting the error
post the full traceback in error tags
(Dec-21-2019, 08:56 AM)buran Wrote: [ -> ] (Dec-21-2019, 08:29 AM)fullstop Wrote: [ -> ]Even when I fix it I am getting the error
post the full traceback in error tags
hi
my only problem is what is happening in config["PATHS"].folder_path = path
obviously you don't want help.
Post the traceback.
Or try Larz solution, which WORKS
config["PATHS"].folder_path
is invalid syntax as he explains
As mention can not use
.
access as the dictionary return has not
folder_path
mapped to it.
Guess
get
would work.
Quick test.
import configparser
config = configparser.ConfigParser()
config.read("abc.ini", encoding="utf-8")
config.sections()
>>> config["PATHS"]["folderPath"]
'None'
# Using get
>>> config["PATHS"].get('folderPath')
'None'
>>> path = 'eggs'
>>> config["PATHS"]["folderPath"] = path
>>> config["PATHS"].get('folderPath')
'eggs'
>>> # Using get can handle errors to
>>> config["PATHS"].get('foo', 'Not in config ini file')
'Not in config ini file'
I have a config file (abc.ini) as below. It just have one Section with an item name= None
[Section]
name = None
Now I am calling this in my main python code as below
import configparser
config = configparser.ConfigParser()
config.read("abc.ini",encoding="utf-8")
config["Section"].new_var = "surname"
Now my problem is with last line of code. This works ok. If I check the type config["Section"].new_var, it is of class str. Now if new_var is not a method or attribute of config["Section"], how it works OK.
Also, it it not adding any item to Section. I mean if I do
print(config["Section"]["new_var"]), I will give an error