python ConfigParser read file doesn't exist

Cacheing picture Cacheing · Aug 6, 2013 · Viewed 17.8k times · Source
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' doesn't exist? Why doesn't this method throw exception?

How can I make it throw exception if the file doesn't exist?

Answer

Nick Humrich picture Nick Humrich · Jul 18, 2014

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.