aJazz
aJazz

Reputation: 115

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

I want to dump a dictionary to a YAML file but my umlauts get messed up.

Here is the code:

import ruamel.yaml

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

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

The output is for example:

Testdurchf�hrung

I want the ouptut in the file to be this:

Testdurchführung

However, when I use this it works:

import sys
import ruamel.yaml

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

Output to console is:

Testdurchführung

How can I solve this?

Upvotes: 1

Views: 866

Answers (1)

Anthon
Anthon

Reputation: 76692

When you open a file on Windows using 'w' it will write a text file, but ruamel.yaml by default writes a binary UTF-8 encoded file.

On sys.stdout that normally works (unless your terminal doesn't support UTF-8), so you don't see the problem there.

You should either open the file for output using:

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

or use a pathlib.Path instance:

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

Upvotes: 1

Related Questions