pyyaml正在产生不需要的!! python/unicode输出

edA*_*a-y 24 python pyyaml

我正在使用pyyaml将对象转储到文件中.对象中有几个unicode字符串.我以前做过这个,但现在它正在生成这样的输出项:

'item': !!python/unicode "some string"
Run Code Online (Sandbox Code Playgroud)

而不是期望的:

'item': 'some string'
Run Code Online (Sandbox Code Playgroud)

我打算输出为utf-8.我使用的当前命令是:

yaml.dump(data,file(suite_out,'w'),encoding='utf-8',indent=4,allow_unicode=True)
Run Code Online (Sandbox Code Playgroud)

在其他地方,我做以下工作:

codecs.open(suite_out,"w","utf-8").write(
    yaml.dump(suite,indent=4,width=10000)
)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Python 2.7.3

edA*_*a-y 40

我尝试了很多组合,我能找到的唯一能够始终生成正确YAML输出的组合是:

yaml.safe_dump(data, file(filename,'w'), encoding='utf-8', allow_unicode=True)
Run Code Online (Sandbox Code Playgroud)

  • `yaml.safe_dump(data,stream)`对我来说已经足够了. (6认同)
  • 稍微适应Python 3.6,它工作得很好: `yaml.safe_dump({"key" : "foo"}, open("test3.out",'w'), allowed_unicode=True)` 编码似乎没有必要的,可能是因为Python3中的默认文本文件编码,但是如果没有`allow_unicode`,您会在文件中得到`"foo\U0001F9E8"`。` (2认同)