The examples in this article describe how Python reads and writes the INI file. Share to everyone for your reference. Specifically as follows:
For example, there is a file Update.ini, which has these contents:
?
1 2 3 4 5 6 7 8 |
[ZIP] Engineversion=0 datversion=5127 Filename=dat-5127.zip filepath=/pub/antivirus/datfiles/4.x/filesize=13481555 CHECKSUM=6037,021E md5=aaeb519d3f276b810d46642d782d8921 |
Then you can get the value of MD5 by the following code, easy.
?
1 2 3 4 5 6 7 |
#!/usr/bin/env python #-*-coding:utf-8-*-import configparser config = Configparser.configparser () CONFIG.READFP ( ' Update.ini ') a = Config.get ("ZIP", "MD5") print a |
Writing is also very simple:
?
1 2 3 4 5 6 7 8 9 10 |
Import Configparser config = Configparser.configparser () # Set a number of parameters Config.add_section ("book") config.se T ("book", "title", "The Python Standard Library") Config.set ("book", "Author", "Fredrik Lundh") Config.add_section (" Ematter ") Config.set (" Ematter "," pages ",) # Write to File Config.write (open (' 1.ini ', ' W ')) |
Modification is not difficult (add content):
?
1 2 3 4 5 6 7 8 |
#!/usr/bin/env python #-*-coding:utf-8-*-import configparser config = Configparser.configparser () config.read (' 1.ini ' A = Config.add_section ("MD5") Config.set ("MD5", "value", "1234") config.write (Open (' 1.ini ', ' r+ ')) #可以把r + change to other ways to see the result :) |
Modify Content:
?
1 2 3 4 5 6 7 |
#!/usr/bin/env python #-*-coding:utf-8-*-import configparser config = Configparser.configparser () config.read (' 1.ini ' ) Config.set ("MD5", "value", "Kingsoft") #这样md5就从1234变成kingsoft了 config.write (open (' 1.ini ', ' r+ ')) |
Delete part is lazy to write, interested in their own look at the document:
Remove_option (section, option)
Remove The specified option from the specified section. If The section does is not exist, raise nosectionerror. If the option existed to is removed, return True; otherwise return False. New in version 1.6.
Remove_section (section)
Remove the specified section from the configuration. If The section is fact existed, return True. otherwise return False.