Practice content:
Use Python to manage INI files: Implement queries, add, delete, save operations.
Practice Purpose:
1. Master the basic operation of the file
2. Recognize the INI file
3. Understand Configparser;
INI configuration file format:
Section: [Session]
Parameter (key = value)
[Port]
port1=3306
Import Configparser
Cfg=configparser.configparser ()
Vim Test.txt
[UserInfo]
Name=nyan
Pwd=password
[Study]
Python_base=15
Python_junior=30
Linux_base=15
Cfg.read (' Test.txt ')
Cfg.sections ()
Cfg.items
For SE in cfg.sections ():
Print SE
Print Cfg.items (SE)
Cfg.set (' userinfo ', ' pwd ', ' passw0rd '): Modify
Cfg.set (' userinfo ', ' email ', ' [email protected] '): Insert
Cfg.remove_option (' userinfo ', ' email ')
inimanage.py
Import OS
Import Os.path
Import Confugparser
...
1.dump INI
2.del section
3.del Item
4.modify Item
5.add section
6.save Modify
...
Class Student_info (object):
def __init__ (self.recordfile):
Self.logfile = Recordfile
Self.cfg = Configparser.configparser ()
def cfg_load (self):
Self.cfg.read (Self.logfile)
def cfg_dump (self):
Se_list = Self.cfg.sections ()
Print "================="
For SE in se_list:
Print SE
Print Self.cfg.items (SE)
Print "================="
def delete_item (Self,section,key):
Self.cfg.remove_option (Setion,key)
def delete_section (self, section):
Self.cfg.remove_section (section)
def add_section (self,section):
Self.cfg.add_section (section)
def set_item (Self,section,key,value):
Self.cfg.set (Section,key,value)
def save (self):
fp = Oopen (' Test.txt ', ' W ')
Self.cfg.write (FP)
Dp.close ()
if __name__ = = ' __main__ ':
info = student_info (' test.txt ')
Info.cfg_load ()
Info.cfg_dump ()
Info.set_item (' userinfo ', ' pwd ', ' passw0rd ')
Info.cfg_dump ()
Info.add_section (' login ')
Info.set_item (' login ', ' 2015-0511 ', ' 20 ')
Info.cfg_dump ()
Info.save ()
Python file Exercises