ini_operate.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import configparser
  2. import os
  3. from threading import Lock
  4. class ConfigIni:
  5. def __init__(self, filename):
  6. self.filename = filename
  7. if not os.path.exists(self.filename):
  8. # 如果不存在,创建文件并写入初始内容
  9. with open(self.filename, 'w', encoding='utf-8') as config_file:
  10. config_file.write("# 示例配置文件\n")
  11. self.config = configparser.ConfigParser()
  12. self.lock = Lock()
  13. self.load()
  14. def load(self):
  15. with open(self.filename, 'r', encoding='utf-8') as configfile:
  16. self.config.read_file(configfile)
  17. def save(self):
  18. with open(self.filename, 'w', encoding='utf-8') as configfile:
  19. self.config.write(configfile)
  20. def get(self, section, key, default=""):
  21. with self.lock:
  22. try:
  23. if not self.config.has_option(section, key):
  24. return default
  25. return self.config.get(section, key)
  26. except (configparser.NoSectionError, configparser.NoOptionError):
  27. return default
  28. def get_int(self, section, key, default="0"):
  29. return int(self.get(section, key, default))
  30. def set(self, section, key, value):
  31. with self.lock:
  32. if not self.config.has_section(section):
  33. self.config.add_section(section)
  34. self.config.set(section, key, value)
  35. self.save()
  36. def set_int(self, section, key, value):
  37. self.set(section, key, str(value))
  38. def get_section_keys(self, section):
  39. with self.lock:
  40. if self.config.has_section(section):
  41. return dict(self.config.items(section))
  42. else:
  43. return {}