简体   繁体   English

python ConfigParser读取文件不存在

[英]python ConfigParser read file doesn't exist

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

This is how we read a configuration file in Python.这就是我们在 Python 中读取配置文件的方式。 But what if the 'test.ini' doesn't exist?但是如果“test.ini”不存在呢? Why doesn't this method throw exception?为什么这个方法不抛出异常?

How can I make it throw exception if the file doesn't exist?如果文件不存在,如何让它抛出异常?

You could also explicitly open it as a file.您也可以显式地将其作为文件打开。

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

EDIT: Updated for python 3.编辑:为 python 3 更新。

From the docs :文档

If none of the named files exist, the ConfigParser instance will contain an empty dataset.如果不存在任何命名文件,则ConfigParser实例将包含一个空数据集。

If you want to raise an error in case any of the files is not found then you can try:如果您想在找不到任何文件的情况下引发错误,则可以尝试:

files = ['test1.ini', 'test2.ini']
dataset = config.read(files)
if len(dataset) != len(files):
    raise ValueError("Failed to open/find all config files")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM