Python Note 15-ini configuration file (Configparser)

Source: Internet
Author: User
Tags read ini file

Objective

Using configuration files to flexibly configure some parameters is a common thing, configuration file parsing is not complicated, especially in Python, in the official release of the library contains a library to do this thing, that is Configparser

The format of the Configparser parsing configuration file is compared to the configuration file format of INI, that is, the file is composed of multiple sections, and there are multiple configuration items under each section

Ini

The 1.ini configuration file format is as follows:

;这里是注释[section0]key0 = value0key1 = value1[section1]key2 = value2key3 = value3

2.section can not be repeated, the inside data through the section to find, each seletion may have more than one key and the Vlaue value pairs, comments in English semicolon (;)

Configparser

1.python3 with Configparser module to read INI file

# python3import configParser

Note: The version of Python2 is Configparser

# python2import ConfigParser

2. In Pycharm, create a new INI file: Right-new->file, input box directly write an. ini suffix file, then write the data

3. Note There are Chinese words, here code with Python2 is a bit different, python2 inside directly conf.read (Cfgpath) on it, Python3 need to add a parameter: encoding= "Utf-8"

Note: If the INI file is written in a number, the default is to read the string

# coding:utf-8# 上海-悠悠# QQ群:588402570import configparserimport oscurpath = os.path.dirname(os.path.realpath(__file__))cfgpath = os.path.join(curpath, "cfg.ini")print(cfgpath)  # cfg.ini的路径# 创建管理对象conf = configparser.ConfigParser()# 读ini文件conf.read(cfgpath, encoding="utf-8")  # python3# conf.read(cfgpath)  # python2# 获取所有的sectionsections = conf.sections()print(sections)  # 返回listitems = conf.items('email_163')print(items)  # list里面对象是元祖

Operation Result:

D:\debug_p3\cfg\cfg.ini['email_qq', 'email_163'][('sender', '[email protected]'), ('psw', '123456'),('port', '465'), ('smtp_server', 'smtp.163.com'), ('receiver', '[email protected]')]
Remove

1. If you want to delete one of the sections, for example I want to delete the port under [email_163]

# 删除一个 section中的一个 item(以键值KEY为标识)conf.remove_option('email_163', "port")

2. Delete the entire section

conf.remove_section('email_163')

3. Reference code:

# coding:utf-8import configparserimport os# 上海-悠悠# QQ群:588402570curpath = os.path.dirname(os.path.realpath(__file__))cfgpath = os.path.join(curpath, "cfg.ini")print(cfgpath)  # cfg.ini的路径# 创建管理对象conf = configparser.ConfigParser()# 删除一个 section中的一个 item(以键值KEY为标识)conf.remove_option('email_163', "port")items = conf.items('email_163')print(items)  # list里面对象是元祖# 删除一个 sectionconf.remove_section('email_163')sects = conf.sections()print(sects)  # list里面对象是元祖

Operation Result:

D:\debug_p3\cfg\cfg.ini[('sender', '[email protected]'), ('psw', '123456'), ('smtp_serve r', 'smtp.163.com'), ('receiver', '[email protected]')]['email_qq']
Add

1. Add a section

# 添加一个selectconf.add_section("emali_tel")print(conf.sections())

2.section added key and value

# 往select添加key和valueconf.set("emali_tel", "sender", "[email protected]")conf.set("emali_tel", "port", "265")
Write writes

1.write write in two ways, one is to delete the original file content, re-write: W

Conf.write (Open (Cfgpath, "w")) # Delete original file re-write

The other is to continue to write the content on the basis of the original file, append mode to write: a

Conf.write (Open (Cfgpath, "a")) # Append mode write

2. The Remove and set methods mentioned above do not actually modify the INI file content, only when the Conf.write () method is executed, the INI file content is modified, for example: Append a section content to the INI file

# coding:utf-8import configparserimport oscurpath = os.path.dirname(os.path.realpath(__file__))cfgpath = os.path.join(curpath, "cfg.ini")print(cfgpath)  # cfg.ini的路径# 创建管理对象conf = configparser.ConfigParser()# 添加一个selectconf.add_section("emali_tel")print(conf.sections())# 往select添加key和valueconf.set("emali_tel", "sender", "[email protected]")conf.set("emali_tel", "port", "265")items = conf.items('emali_tel')print(items)  # list里面对象是元祖conf.write(open(cfgpath, "a"))  # 追加模式写入

After running, you will find that the INI file has been added to the last write content.

Set Modify INI file

1. For example I want to change the port under [email_163] in the front INI file to "Chinese"
Note: This is written in Chinese, it needs to be written in the encoding format: encoding= "Utf-8"

# coding:utf-8import configparserimport os# 上海-悠悠# QQ群:588402570curpath = os.path.dirname(os.path.realpath(__file__))cfgpath = os.path.join(curpath, "cfg.ini")# 创建管理对象conf = configparser.ConfigParser()# 先读出来conf.read(cfgpath, encoding="utf-8")# 修改section里面的值conf.set("email_163", "port", "中文")  # 写入中文conf.write(open(cfgpath, "r+", encoding="utf-8"))  # r+模式

Python Note 15-ini configuration file (Configparser)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.