以.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 = "params.properties"

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

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

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

更多推荐

python 读取.properties文件