您当前的位置:首页 > 计算机 > 编程开发 > Python

python --ini文件的增删改查

时间:08-12来源:作者:点击数:

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')
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐