gpt4 book ai didi

python ConfigParser读取文件不存在

转载 作者:IT老高 更新时间:2023-10-28 20:45:40 33 4
gpt4 key购买 nike

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.ini')

这就是我们在 Python 中读取配置文件的方式。但是如果“test.ini”文件不存在怎么办?为什么这个方法不抛出异常?

如果文件不存在,如何让它抛出异常?

最佳答案

您也可以将其作为文件显式打开。

try:
with open('test.ini') as f:
config.read_file(f)
except IOError:
raise MyError()

编辑:针对 python 3 更新。

关于python ConfigParser读取文件不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090666/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com