Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. But what if the 'test.ini' file doesn't exist? Why doesn't this method throw an exception?

How can I make it throw exception if the file doesn't exist?

like image 632
Cacheing Avatar asked Aug 06 '13 21:08

Cacheing


People also ask

What is Configparser Configparser ()?

Source code: Lib/configparser.py. This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files.

How do I print a Configparser object?

Just use a StringIO object and the configparser's write method. It looks like the only method for "printing" the contents of a config object is ConfigParser. write which takes a file-like object.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.


2 Answers

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.

like image 134
Nick Humrich Avatar answered Sep 27 '22 19:09

Nick Humrich


From the docs:

If none of the named files exist, the ConfigParser instance will contain an empty dataset.

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") 
like image 40
Ashwini Chaudhary Avatar answered Sep 27 '22 19:09

Ashwini Chaudhary