read_properties.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: Deepcold
  5. @file: test_ymal.py
  6. @time: 2019/8/16 18:33
  7. """
  8. class Properties(object):
  9. def __init__(self, fileName):
  10. self.fileName = fileName
  11. self.properties = {}
  12. def __getDict(self, strName, dictName, value):
  13. if (strName.find('.') > 0):
  14. k = strName.split('.')[0]
  15. dictName.setdefault(k, {})
  16. return self.__getDict(strName[len(k) + 1:], dictName[k], value)
  17. else:
  18. dictName[strName] = value
  19. return
  20. def getProperties(self):
  21. try:
  22. pro_file = open(self.fileName, 'Ur')
  23. for line in pro_file.readlines():
  24. line = line.strip().replace('\n', '')
  25. if line.find("#") != -1:
  26. line = line[0:line.find('#')]
  27. if line.find('=') > 0:
  28. strs = line.split('=')
  29. strs[1] = line[len(strs[0]) + 1:]
  30. self.__getDict(strs[0].strip(), self.properties, strs[1].strip())
  31. except Exception as e:
  32. raise e
  33. else:
  34. pro_file.close()
  35. return self.properties
  36. dictProperties = Properties("application-dev.properties").getProperties()
  37. print(dictProperties)