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

扶醉桌前 提交于 2020-01-13 11:30:12

问题


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


回答1:


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"))



回答2:


You are right, and I am wrong. My solution of testing the length of the list returned is not a bad solution, and it will work around the outlier case where none of the files exists, but my question suggests that I did not do a good job of reading the documentation.



来源:https://stackoverflow.com/questions/46868616/python-3-configparser-read-does-not-raise-an-exception-when-given-a-non-existi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!