Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 544
Jeff Silverman Avatar asked Jan 29 '23 09:01

Jeff Silverman


1 Answers

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"))
like image 61
Lawrence D'Oliveiro Avatar answered Jan 31 '23 23:01

Lawrence D'Oliveiro