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

该文章展示了如何使用Python读取.properties配置文件,定义了一个Properties类,通过打开文件、解析键值对并存储到字典中来获取文件内容。然后,文章给出了一个实例,从params.properties文件中提取host、port等参数,并处理多行字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值