解决:
改成用2进制读取yaml文件:
with open(r"D:\file\yaml\data.yml",'rb') as f:
读取代码如下:
'''读取yaml方法''' import yaml def read_file(file_path): with open(file_path,'r',encoding='utf-8') as f: data = yaml.load(f,Loader=yaml.FullLoader) return data if __name__ == '__main__': #print(read_file('..\conf\db_conf.yml')) print(read_file(r'..\test_data\login\login_data.yml'))
写入yaml文件的方法:
'''写入yaml方法''' import yaml def main(): data = { 'search_data':{ 'search_tast_002':'test你', } } with open("./text.yml","w") as f: yaml.dump(data,f,encoding="utf-8",allow_unicode=True) # 加后2个参数解决中文乱码 if __name__ == '__main__': main()
通用读取和写入的方法:
import yaml import io class OperationYaml(): '''操作YML文件''' def __init__(self): yaml.warnings({'YAMLLoadWarning': False}) def read_yml(self, read_yml_path): with io.open(read_yml_path, 'r', encoding="utf-8") as rf: yml_data = yaml.load(rf) return yml_data def write_yml(self, write_yml_path, write_yml_data): with io.open(write_yml_path, 'w', encoding="utf-8") as wf: yaml.dump(write_yml_data, wf) if __name__ == '__main__': data = {'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1} # OperationYaml().write_yml(r'ssa.yml',data) d = OperationYaml().read_yml('ss.yml') print(d)