当我尝试使用 configparser.read 读取不存在的文件时,我认为它应该引发异常。它没有。它返回一个空列表。显然,我可以测试一个空列表并引发异常。如果 configparser.read 引发 FileNotFound 异常,在我看来它更直观和更安全。
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']
>>>
谢谢
最佳答案
如documentation明确地说,您可以将任意数量的文件名传递给 read
方法,它会默默地忽略那些无法打开的。
如果您想看到打开文件失败的异常,请尝试 read_file
方法代替:
config.read_file(open("xyzzy.xyz", "r"))
关于python 3 configparser.read() 在给定不存在的文件时不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46868616/