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

标签 python configparser

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

相关文章:

python - 将图像分为径向部分并选择单个部分中的值

python - 在 Python 中使用协程进行并行编程

python - 从 config.ini 文件中获取列表

Python ConfigParser 检查部分和键值是否存在

Python ConfigParser 模块重命名一个部分

python - 如何混合tensorflow keras模型和变压器

python - 在 gunicorn 中运行时,Flask 应用程序记录器无法正常工作

python - Pandas 数据框返回列字符串中的第一个单词

python - 使用 python "ConfigParser"编辑 ini 文件会将所有 ini 条目替换为较低的键

python - MissingSectionHeaderError : File contains no section headers. (configparser)