Python 3 configparser.read() 在给定不存在的文件时不会引发异常



当我尝试使用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']
 >>>

谢谢

正如文档所明确指出的,您可以将任意数量的文件名传递给 read 方法,它将静默地忽略无法打开的文件名。

如果要查看无法打开文件的异常,请尝试使用 read_file 方法:

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

最新更新