Python读取value值是多行的Properties文件

首先是Python读取Properties文件代码

# 读取Properties文件类
class Properties:
    def __init__(self, file_name):
        self.file_name = file_name
 
    def getProperties(self):
        try:
            pro_file = open(self.file_name, 'r', encoding='utf-8')
            properties = {}
            for line in pro_file:
                if line.find('=') > 0:
                    strs = line.replace('\n', '').split('=')
                    properties[strs[0]] = strs[1]
        except Exception as e:
            raise e
        else:
            pro_file.close()
        return properties

# .properties文件在源码同级的路径下
properties_path = "params.properties"
 
# 声明一个Properties类的实例,调用其getProperties方法,返回一个字典
properties = Properties.Properties(properties_path).getProperties()
 
# 所有参数都存在字典的value中
host = properties['host']
port= properties['port']
user = properties['username']
password = properties['password']
dbname= properties['dbname']
sql= properties['sql']

params.properties文件

# int类型则要加强制类型转换
host=127.0.0.1

port=3306
user=root
password=root

dbname=my_sql

#value是多行,后加\,切记\必须放在一行的最后

sql=select *     \

from tb_test
 

你可能感兴趣的:(Python,python)