Search code examples
pythonyamlpyyaml

Yaml safe load special character ° from file


I am trying to read a yml config file using PyYAML. See below example of such a file. The desired field may contain a special character, such as °. The resulting string in below example is not the desired °C, but rather °C.

The goal is to only read °C. I have control over the config file, so escaping or quoting is not a problem. Also decoding, replacing or other operations afterwards are possible, but they should also work for strings without special characters and strings with other special characters.

So far I had no success down this road however.

Example

test.yml

super_important_variable: °C

Code

import yaml
with open('test.yml', 'r') as open_yml:
    print(yaml.safe_load(open_yml))

Current result

{'super_important_variable': '°C'}

Desired result

{'super_important_variable': '°C'}

The weird thing is that this returns the correct result:

import yaml
yml_str = "super_important_variable: °C"
yaml.safe_load(yml_str)

> {'super_important_variable': '°C'}

Solution

  • Try this:

    import yaml
    with open('test.yaml', 'r', encoding='utf-8') as open_yml:
        print(yaml.safe_load(open_yml))
    

    More here about encoding and files in python: Unicode (UTF-8) reading and writing to files in Python