Python reads the INI configuration file and saves it to the object properties

cuntou0906 2021-04-06 17:36:36
python reads ini configuration file


Python Read ini The configuration file

Reading configuration ini file , Save to the properties of the object

Because you often need to set some variables , If you put it directly in the main program , A bunch of variables , Inconvenient to manage . therefore , adopt ini How to configure files , Automatically read the information in the configuration file and save it to the object , Easy to manage and call , Later, you can use this variable by calling object properties directly . Here's the code and an example ~~

import configparser
###################################################################################################
# IniConf analysis Ini file Store all configuration information as variables in In an object , Easy to manage 
# Generally, values that do not change frequently are passed through IniConf Read 
# Sample file template :
# [url] ; section name 
# baidu = 'https://www.jb51.net'
# port = 80
#
# [email]
# sender = 'xxx@qq.com'
## [tan]
# (1) Every session Next there's an assignment statement 
# (2) Strings need single quotes , Otherwise, it cannot be parsed 
# (3) The generated variable is named :session name _items name , And deposit in IniConf In the object 
# for example : Aforementioned port The corresponding variable name :url_port = 80
# (4) If a session There is no corresponding property statement under , Then session Do not perform any assignment properties 
# (4) Attention: Some session You cannot add spaces at the beginning of the assignment statement under !!!! Otherwise, the variable cannot be resolved 
###################################################################################################
class IniConf():
def __init__(self,filename):
self.filename = filename # Pathname 
self.getConf() # analysis 
pass
def getConf(self):
try:
con = configparser.ConfigParser()
con.read(self.filename, encoding='utf-8') # Read the file 
print('Get Ready to read ' + self.filename + '...')
pass
except:
print('Error happend...')
sections = con.sections() # Get all section
# print('sessions:',sections)
for sc in sections: # Cycle each Session
items = con.items(sc) # The return result is tuple 
if len(items)==0: # The length is 0 It means that session There is no attribute 
pass
else: # The length is not 0 It means that session There are properties 
for it in items: # Loop traversal Each attribute 
loc = 'self.' + sc + '_' + it[0] +' = ' + it[1] # Generate the corresponding attribute assignment variable statement 
exec(loc) # Execute statement 
pass
print('Get Conf Successfully!\n')
self.toString()
pass
def toString(self): # Print all properties key = value
print('All Conf Parameters:')
for dic in self.__dict__:
print(' ',dic,':',self.__dict__[dic])
pass
pass
if __name__ == '__main__':
filename = './Resource/conf.ini' # File path 
IniConfBoj = IniConf(filename = filename) # Object
# IniConfBoj.toString() # Print all properties 
pass

ini The documents are as follows :

[url] ; section name 
baidu = 'https://www.jb51.net'
port = 80

[email]
sender = 'xxx@qq.com'

[tan]

result :

Get Ready to read ./Resource/conf.ini...
Get Conf Successfully!
All Conf Parameters:
filename : ./Resource/conf.ini
url_baidu : https://www.jb51.net
url_port : 80
email_sender : xxx@qq.com
Process finished with exit code 0
版权声明
本文为[cuntou0906]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210406173417258I.html

  1. 商业数据分析从入门到入职(7)Python基础数据结构及其操作
  2. 商业数据分析从入门到入职(6)Python程序结构和函数
  3. Business data analysis from entry to entry (9) Python Network Data Acquisition
  4. Business data analysis from entry to entry (8) Python module, file IO and object oriented
  5. Business data analysis from entry to entry (7) Python basic data structure and its operation
  6. Business data analysis from entry to entry (6) Python program structure and function
  7. 简简单单实现 Python Web 的登录注册页面,还包含一半逻辑。
  8. Simple implementation of Python web login registration page, but also contains half of the logic.
  9. 什么是pip?Python新手入门指南
  10. What is PIP? Getting started with Python
  11. Python uses for... Else to jump out of double nested loop
  12. Python基础之:Python中的内部对象
  13. 人工智能入门:Python实现机器学习
  14. The foundation of Python: inner objects in Python
  15. Introduction to artificial intelligence: machine learning in Python
  16. Python基础之:Python中的内部对象
  17. The foundation of Python: inner objects in Python
  18. Python 小技之 Office 文件转 PDF
  19. 还在为多张Excel汇总统计发愁?Python 秒处理真香!
  20. 用 Python 制作音乐聚合下载器
  21. Spark Delta Lake 0.4.0 发布,支持 Python API 和部分 SQL
  22. How to transfer office files to PDF
  23. Are you still worried about multiple excel summary statistics? Python second processing really fragrant!
  24. Making music aggregate downloader with Python
  25. Spark delta Lake 0.4.0 is released, supporting Python API and part of SQL
  26. Python信息搜集
  27. Python information gathering
  28. Python - 关于类(self/cls) 以及 多进程通讯的思考
  29. Python - thinking about class (self / CLS) and multi process communication
  30. Python - 关于类(self/cls) 以及 多进程通讯的思考
  31. Python - thinking about class (self / CLS) and multi process communication
  32. Python信用评分卡建模(附代码)
  33. Python credit score card modeling (with code)
  34. 学Python需要学数据库吗?Python学习教程!
  35. Do you need to learn database to learn Python!
  36. Python私有变量如何定义?Python学习教程!
  37. How to define Python private variables? Python tutorial!
  38. Python数据分析入门(六):Pandas的函数应用
  39. Introduction to Python data analysis (6): function application of pandas
  40. 学Python需要学数据库吗?Python学习教程!
  41. Do you need to learn database to learn Python!
  42. Python描述 LeetCode 80. 删除有序数组中的重复项 II
  43. C++/python描述 AcWing 94. 递归实现排列型枚举
  44. C++/python描述 AcWing 92. 递归实现指数型枚举
  45. Python描述 LeetCode 88. 合并两个有序数组
  46. 苏州大学计算机考研 复试机试真题2013-2021真题及Python题解
  47. Python描述 LeetCode 781. 森林中的兔子
  48. 字典和json的区别是什么?Python学习
  49. Python describes leetcode 80. Removing duplicate items from ordered arrays II
  50. C + + / Python description acwing 94. Recursive implementation of permutation enumeration
  51. C + + / Python description acwing 92. Recursive implementation of exponential enumeration
  52. Python describes leetcode 88. Merging two ordered arrays
  53. Real computer test questions 2013-2021 of computer postgraduate entrance examination of Soochow University and python solutions
  54. The rabbit in the forest
  55. Python中的魔法属性
  56. What's the difference between dictionary and JSON? Python learning
  57. Magic properties in Python
  58. 字典和json的区别是什么?Python学习
  59. What's the difference between dictionary and JSON? Python learning
  60. python刷题-字母图形