python --ini文件的增删改查
- import configparser
-
- class MyINIFile:
- def __init__(self, filename):
- self.filename = filename
- self.config = configparser.ConfigParser()
- self.config.read(self.filename)
-
- def read_value(self, section, key):
- try:
- return self.config.get(section, key)
- except configparser.Error as e:
- print(f"Error reading value: {e}")
- return None
-
- def write_value(self, section, key, value):
- try:
- if not self.config.has_section(section):
- self.config.add_section(section)
- self.config.set(section, key, value)
- with open(self.filename, 'w') as configfile:
- self.config.write(configfile)
- except configparser.Error as e:
- print(f"Error writing value: {e}")
-
- def delete_value(self, section, key):
- try:
- if self.config.has_section(section) and self.config.has_option(section, key):
- self.config.remove_option(section, key)
- with open(self.filename, 'w') as configfile:
- self.config.write(configfile)
- else:
- print(f"Section '{section}' or option '{key}' does not exist.")
- except configparser.Error as e:
- print(f"Error deleting value: {e}")
-
- def update_value(self, section, key, value):
- try:
- if self.config.has_section(section) and self.config.has_option(section, key):
- self.config.set(section, key, value)
- with open(self.filename, 'w') as configfile:
- self.config.write(configfile)
- else:
- print(f"Section '{section}' or option '{key}' does not exist.")
- except configparser.Error as e:
- print(f"Error updating value: {e}")
-
- # Example usage:
- filename = 'example.ini'
- config = MyINIFile(filename)
-
- # Write a value
- config.write_value('Section1', 'user', '111')
-
- # Read a value
- value = config.read_value('Section1', 'user')
- print(f"Read value: {value}")
-
- # Update a value
- config.update_value('Section1', 'key1', 'new_value')
-
- # Delete a value
- config.delete_value('Section1', 'key1')
-