the Configparser module can handle data like the MySQL configuration file format
The following is the initial configuration file content for MySQL:
[Email protected] ~]# CAT/ETC/MY.CNF
[Mysqld]
Datadir=/var/lib/mysql
Socket=/var/lib/mysql/mysql.sock
User=mysql
Symbolic-links=0
[Mysqld_safe]
Log-error=/var/log/mysqld.log
Pid-file=/var/run/mysqld/mysqld.pid
Next, use the Configparser module to generate the file in such a format:
#!/usr/local/python3/bin/python3
Import Configparser
Config = Configparser. Configparser ()
config["mysqld"] = {"DataDir": "/var/lib/mysql",
"Socket": "/var/lib/mysql/mysql.sock",
"User": "MySQL",
"Symbolic": "0"}
config["Mysql_safe"] = {"Log-error": "/var/log/mysqld.log",
"Pid-file": "/var/run/mysqld/mysqld.pid"
}
With open ("My.cnf", "W") as F:
Config.write (f)
Execute the script, you can generate a local and my.cnf-like file.
After that, let's see how to read
>>> Import Configparser
>>> config = configparser. Configparser ()
>>> config.read ("my.cnf")//equivalent to loading files
[' MY.CNF ']
>>> config.sections ()//View all the keys in the file, formatted like [mysqld], [Mysql_safe]
[' mysqld ', ' Mysql_safe ']
>>> config["Mysqld" ["DataDir"]//Get value
'/var/lib/mysql '
>>> "mysqld" in Config//determine if a key is in a file
True
>>> for I in config["mysqld"]://loop print all values under key
... print (i)
...
DataDir
Socket
User
Symbolic
After that, let's take a look at the changes.
>>> Import Configparser
>>> config = configparser. Configparser ()
>>> config.read ("my.cnf")
[' MY.CNF ']
####### #读取 ##########
>>> secs = config.sections ()
>>> Print (secs)
[' mysqld ', ' Mysql_safe ']
>>> options = config.options ("mysqld")//print "All keys under Mysqld"
>>> Print (options)
[' DataDir ', ' socket ', ' user ', ' symbolic ']
>>> item_list = Config.items ("mysqld")//Print all values under "mysqld"
>>> Print (item_list)
[(' DataDir ', '/var/lib/mysql '), (' Socket ', '/var/lib/mysql/mysql.sock '), (' User ', ' MySQL '), (' Symbolic ', ' 0 ')]
>>> val = config.get ("mysqld", "DataDir")//print the value of a key
>>> Print (val)
/var/lib/mysql
>>> val = config.getint ("mysqld", "symbolic")
>>> Print (val)
0
##### #修改 ######
>>> sec = config.remove_section ("mysqld")//is equivalent to removing all of the "mysqld" fields
>>> config.write (Open ("My.cnf", "w"))
>>> sec = config.add_section ("mysqld")//Add a field to the end of the file [mysqld]
>>> config.write (Open ("My.cnf", "w"))
>>> config.set ("Mysqld", "User", "root")//Added user=root under the [Mysqld] field
>>> config.write (Open ("My.cnf", "w"))
>>> config.remove_option ("mysqld", "user")//Remove user=root from [mysqld] Field
True
>>> config.write (Open ("My.cnf", "w"))
Python configparser module