31
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?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Cacheing
  • 3,431
  • 20
  • 46
  • 65
  • A one-liner solution has been suggested in [python 3 configparser.read() does not raise an exception when given a non-existing file](https://stackoverflow.com/a/46869892/5433628). (It's for one file only, but could easily be extended to multible files with an iterator.) – ebosi Nov 07 '19 at 17:35

2 Answers2

32

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.

Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
  • 7
    This worked. By the way: `readfp()` is obsolete now (at least in Python 3). It is now called `read_file()`. – Terje Mikal Jul 26 '16 at 18:24
  • 1
    Update Nov2019/python 3, beware/adapt accordingly: DeprecationWarning: This method will be removed in future versions. Use 'parser.read_file()' instead. – user2305193 Nov 27 '19 at 20:09
22

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")
Burathar
  • 5
  • 5
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504