python ConfigParser read file doesn't exist
Question:
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.ini')
This is how we read a configuration file in Python. But what if the ‘test.ini’ file doesn’t exist? Why doesn’t this method throw an exception?
How can I make it throw exception if the file doesn’t exist?
Answers:
From the docs:
If none of the named files exist, the ConfigParser
instance will
contain an empty dataset.
If you want to raise an error in case any of the files is not found then you can try:
files = ['test1.ini', 'test2.ini']
dataset = config.read(files)
if len(dataset) != len(files):
raise ValueError("Failed to open/find all config files")
You could also explicitly open it as a file.
try:
with open('test.ini') as f:
config.read_file(f)
except IOError:
raise MyError()
EDIT: Updated for python 3.
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.ini')
This is how we read a configuration file in Python. But what if the ‘test.ini’ file doesn’t exist? Why doesn’t this method throw an exception?
How can I make it throw exception if the file doesn’t exist?
From the docs:
If none of the named files exist, the
ConfigParser
instance will
contain an empty dataset.
If you want to raise an error in case any of the files is not found then you can try:
files = ['test1.ini', 'test2.ini']
dataset = config.read(files)
if len(dataset) != len(files):
raise ValueError("Failed to open/find all config files")
You could also explicitly open it as a file.
try:
with open('test.ini') as f:
config.read_file(f)
except IOError:
raise MyError()
EDIT: Updated for python 3.