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

空扰寡人 提交于 2019-12-04 15:21:32

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

pip install configparser

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
Shubham Chaudhary

You can use the configparser2 module, which is a fork of the configparser backport maintained by me. Add it in your requirements or do pip install configparser2 and then use something as simple as:

try:
    import configparser
except ImportError as e:
    import configparser2 as configparser
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!