栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 读取.properties文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 读取.properties文件

        以.properties为后缀名的文件是在Java开发中非常常用的一种用于存储可变参数的文件类型,例如不同环境的ip地址、端口号、账号密码,又或者是模型的超参数,都可以保存在这类文件中,这样就不需要先在代码中找到每个变量的位置再进行修改了。同样,在Python开发中也可以借鉴这个文件类型(当然Java还有很多优秀的编程思想,非常值得借鉴),只需要写一个读取文件的py程序。

        1. 编写读取.properties的文件:

        Properties.py

# 读取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

        2. 编写.properties文件

        params.properties

# =号左右不加空格,=号右侧的值读取出来默认是字符串,不需要加""
# 如果需要int类型则要加强制类型转换
host=x.x.x.x
user=yourname
password=yourpassword

EPOCH=100
BATCH_SIZE=64
LR=0.02

        3.调用Properties类

        main.py

# .properties文件的路径
properties_path = "dynamic_resource_allocation.properties"

# 声明一个Properties类的实例,调用其getProperties方法,返回一个字典
properties = Properties.Properties(properties_path).getProperties()

# 所有参数都存在字典的value中
host = properties['host']
user = properties['username']
password = properties['password']

# 转成int类型
EPOCH = int(properties['EPOCH'])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/329938.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号