Python Yaml 写入中文乱码的问题

 

 

 

问题背景:

  在执行测试用例,将测结果回写到yaml文件时,出现中文全都是Unicode编码的问题。

如下:

test.yaml文件内容

Data:
  name: "中国"
  cityName: "上海"
  areaName: "闵行区"

 

读写代码如下

# FileName : writeYaml.py
# Author   : Adil
# DateTime : 2020/4/26 6:37 PM
# SoftWare : PyCharm

import yaml



yamlFile = 'test.yaml'

f = open(yamlFile,'r',encoding='utf-8')

cont = f.read()

r = yaml.safe_load(cont)
print(r)


f.close()


fw = open(yamlFile,'a',encoding='utf-8')

w = r

yaml.dump(w,fw)

fw.close()

 

执行代码如下

 

 

执行后yaml 文件内容变更为

 

 

 

解决办法

加入参数 

allow_unicode=True
fw = open(yamlFile,'a',encoding='utf-8')

w = r

yaml.dump(w,fw,allow_unicode=True)


fw.close()

 

执行结果

 

 

posted @ 2020-04-26 19:28  Blue·Sky  阅读(8177)  评论(0编辑  收藏  举报