Jeff Silverman
Jeff Silverman

Reputation: 724

python 3 configparser.read() does not raise an exception when given a non-existing file

When I attempt to read a non-existing file using configparser.read, I think it ought to raise an exception. It doesn't. It returns an empty list instead. Obviously, I can test for an empty list and raise an exception. It just seems to me to be more intuitive and safer if the configparser.read raised a FileNotFound exception.

jeffs@jeffs-laptop:~/nbmdt (blue-sky)*$ python3.6
Python 3.6.2 (default, Oct  2 2017, 16:51:32)  [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux 
Type "help", "copyright", "credits" or "license" for more information.
 >>> import configparser
 >>> config=configparser.ConfigParser()
 >>> config.read("xyzzy.xyz")
[]
 >>> config.read("nbmdt.ini")
 ['nbmdt.ini']
 >>>

Thank you

Upvotes: 4

Views: 2986

Answers (1)

Lawrence D'Oliveiro
Lawrence D'Oliveiro

Reputation: 2794

As the documentation makes clear, you can pass any number of filenames to the read method, and it will silently ignore the ones that cannot be opened.

If you want to see an exception on failure to open the file, try the read_file method instead:

config.read_file(open("xyzzy.xyz", "r"))

Upvotes: 10

Related Questions