美文网首页python之路
python操作yaml文件

python操作yaml文件

作者: 非鱼2018 | 来源:发表于2020-03-22 12:41 被阅读0次

    之前一直使用的py文件当配置文件用的,优点就是使用方便,直接导入该py文件就可以使用,但有时候实在分不清哪些变量是配置文件里的
    也使用过configparse读取配置文件,感觉有点太繁琐
    相对来说,yaml文件格式比较灵活,作为配置文件,读取也比较简单

    yaml文件内容

    user: feiyu1009
    password: 123456
    
    urls:
     baid: http://www.baidu.com
     google: http://gooogle.com
    
    datas:
    - a
    - b
    
    ---
    name: feiyu2009
    

    需要先安装
    pip install PyYaml

    #coding=utf-8
    import yaml
    import os
    
    file_path='comfig.yaml'
    # 读取单个yaml文件数据
    def get_yaml_data(file):
        try:
    
            with open(file,'r',encoding='utf-8') as f:
                try:
                    yfile=yaml.safe_load(f)
                except yaml.scanner.ScannerError as e:
                    print('读取错误:',str(e))
                else:
                    return yfile
        except FileNotFoundError:
            print('文件不存在')
    
    #读取一个yaml文件包含多个yaml文档
    def get_yaml_mutli_data(file):
        try:
    
            with open(file,'r',encoding='utf-8') as f:
                try:
                    yfile=yaml.safe_load_all(f)
                except yaml.scanner.ScannerError as e:
                    print('读取错误:',str(e))
                else:
                    for data in yfile:
                        yield data
    
        except FileNotFoundError:
            print('文件不存在')
    
    # 生成yaml文档
    def write_yaml(file,**kws):
        with open(file,'w',encoding='utf-8') as f:
            yaml.dump(kws,f)
    
    
    if __name__=='__main__':
        print('测试读取单个yaml文件')
        # datas=get_yaml_data(file_path)
        # if datas is not None:
        #     print(datas)
        print('生成yaml文档')
        # datas={"username":'feiyu2009','password':'123456'}
        # write_yaml('config2.yaml',**datas)
        # 读取多个yaml文档
        datas=get_yaml_mutli_data(file_path)
        if datas is not None:
            #print(list(datas))
            print(next(datas))
            print(next(datas))
    

    相关文章

      网友评论

        本文标题:python操作yaml文件

        本文链接:https://www.haomeiwen.com/subject/ryteyhtx.html