使用 yaml.dump 转储字典不会将特殊字符写入 python3 中使用 "with open()" 的文件

dumping dictionary with yaml.dump doesn't write special characters to file with "with open()" in python3

我想将字典转储到 YAML 文件,但我的变音符号搞砸了。

代码如下:

import ruamel.yaml

yaml = ruamel.yaml.YAML()
dictUsed = 'Testdurchführung'

with open(r'C:\Users\somepath', 'w') as outfile:
    yaml.dump(dictUsed, stream=outfile)

输出例如:

Testdurchf�hrung

我希望文件中的输出是这样的:

Testdurchführung

但是,当我使用它时它起作用了:

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
yaml.dump(dictUsed, sys.stdout)

控制台的输出是:

Testdurchführung

我该如何解决这个问题?

当您使用 'w' 打开 Windows 上的文件时,它将写入文本文件,但 ruamel.yaml 默认情况下写入二进制 UTF-8 编码文件。

sys.stdout 上正常工作(除非您的终端不支持 UTF-8),所以您看不到那里的问题。

您应该使用以下方式打开文件进行输出:

with open(r'C:\Users\somepath', 'wb') as outfile:

或使用 pathlib.Path 实例:

import pathlib
p = pathlib.Path(r'C:\Users\somepath')
yaml.dump(dictUsed, p)