4

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

Jeff Silverman
  • 692
  • 1
  • 8
  • 15
  • The docs explain that this is so you can look for a config file in several different places: https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.read. I guess they probably could throw an exception if nothing was found. – fdsa Oct 21 '17 at 22:22
  • also doesn't throw exception when we don't have permissions to view the file's content ... and raise later in the code about "block not found" – Ricky Levi Oct 18 '22 at 09:11

1 Answers1

10

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"))
Lawrence D'Oliveiro
  • 2,768
  • 1
  • 15
  • 13