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/