Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read config(.ini) file in python which will work on 2.7 and 3.x python

Should I use ConfigParser which is compatible with python 2.7 and 3.x or do you suggest any other module in python which is compatible with both versions of python for reading config file?

like image 670
NIlesh Meharkar Avatar asked Feb 26 '26 23:02

NIlesh Meharkar


2 Answers

You can make use of configparser backport, so it will work on both Python version.

pip install configparser
like image 133
Fabio Menegazzo Avatar answered Feb 28 '26 12:02

Fabio Menegazzo


Contrary to the other answers here, you don't need to install any extra packages to write INI-parsing code that is compatible with Python 2 and 3. Python 3.0's configparser is just a renamed version of Python 2's ConfigParser. There have been some extra features added in Python 3.2 and 3.5 (see the latest version of the docs at https://docs.python.org/library/configparser.html) but these are backwards-compatible, so if you're happy with the features of Python 3.0's configparser you can just do

try:
    import configparser
except ImportError:
    # Python 2.x fallback
    import ConfigParser as configparser
like image 29
Mark Amery Avatar answered Feb 28 '26 13:02

Mark Amery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!