I am trying to use configparser
for the first time to save some default values. I'm receiving the error:
configparser.NoOptionError: No option 'inputpath' in section: 'DEFAULT'
Here's the code I've written. The commented out part, "Write the Configuration File," is how the file was created. The output file looks fine to me.
[DEFAULT]
inputpath = Test Line 1
outputpath = Test Line 2
filename = Test Line 3
If I delete the file, as expected I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'config.ini'
import os
import configparser
config = configparser.ConfigParser()
# Write the Configuration File
# config['DEFAULT']['inputpath'] = 'Test Line 1'
# config['DEFAULT']['outputpath'] = 'Test Line 2'
# config['DEFAULT']['filename'] = 'Test Line 3'
# with open('config.ini', 'w') as configfile:
# config.write(configfile)
if os.path.exists('config.ini'):
print('The path exists')
else:
print('The path does not exist')
print("Check Before")
with open("config.ini", "r") as cfile:
for line in cfile.readlines():
print(line)
print("Check After")
print('Sections:')
print(config.sections())
with open("config.ini", "r") as configfile:
config.read(configfile)
inputpath_default = config.get('DEFAULT', 'inputpath')
print('inputpath_default: ' + inputpath_default)
outputpath_default = config.get('DEFAULT', 'outputpath')
print('outputpath_default: ' + outputpath_default)
filename_default = config.get('DEFAULT', 'filename')
print('filename_default: ' + filename_default)
print('Done')
exit()
The output up to the failure is:
The path exists
Check Before
[DEFAULT]
inputpath = Test Line 1
outputpath = Test Line 2
filename = Test Line 3
Check After
Sections:
[]
Traceback (most recent call last):
...
File "/Users/xxxxxx/Config.py", line 31, in <module>
inputpath_default = config.get('DEFAULT', 'inputpath')
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/configparser.py", line 821, in get
raise NoOptionError(option, section)
configparser.NoOptionError: No option 'inputpath' in section: 'DEFAULT'
My problem was that I had coded:
with open("config.ini", "r") as configfile:
config.read(configfile)
Apparently there is no need to issue an explicit open. Changing those two lines to the following resolved my problem:
configfile="config.ini"
config.read(configfile)
Alternatively, the following also worked:
config.read_file(open('config.ini'))