天天看點

python之yaml檔案讀取封裝

yaml檔案的簡單讀取參考:https://blog.csdn.net/hhs_1996/article/details/115828341

以下是對yaml檔案讀取的類封裝

import yaml
import os


class YamlData:
    def __init__(self, file):
        if os.path.isfile(file):
            self.file = file
        else:
            raise FileNotFoundError("檔案不存在")

    @property  # 設定屬性,調用data方法時可通過調用屬性,不需要帶括号
    def data(self):
        with open(file=self.file, mode="r") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
        return data

if __name__ == '__main__':
    yamlPath = r"E:\code\config.yml"
    data = YamlData(yamlPath).data
    print(data)
           

參考:https://www.cnblogs.com/mian-1122/p/14235535.html