我正在尝试使用 PyYAML 读取 yml 配置文件。请参阅下面此类文件的示例。所需字段可能包含特殊字符,例如°
。下面示例中的结果字符串不是所需的 °C
,而是 °C
。
目标是仅读取°C
。我可以控制配置文件,因此转义或引用不是问题。之后也可以进行解码、替换或其他操作,但它们也应该适用于没有特殊字符的字符串和具有其他特殊字符的字符串。
到目前为止,我在这条路上还没有取得成功。
示例
test.yml
super_important_variable: °C
代码
import yaml
with open('test.yml', 'r') as open_yml:
print(yaml.safe_load(open_yml))
当前结果
{'super_important_variable': '°C'}
期望的结果
{'super_important_variable': '°C'}
奇怪的是,这会返回正确的结果:
import yaml
yml_str = "super_important_variable: °C"
yaml.safe_load(yml_str)
> {'super_important_variable': '°C'}
最佳答案
试试这个:
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
关于python - Yaml 从文件中安全加载特殊字符 °,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57687058/