如何使用从 YAML 文件中检索到的 utf-8 文件名用于 os.path.isdir()?

How can I use an utf-8 file name retrieved from a YAML file for os.path.isdir()?

我正在从 config.yml 文件加载文件夹路径。示例名称:C:/Users/Name/Desktop/ü,其中包含一个 utf-8 字符。当我使用 yaml.load(config) 加载此路径时(我正在使用 ruamel.yaml),然后使用加载的值检查此目录是否存在 os.path.isdir() 我总是返回 "False",甚至尽管该文件存在。 (在 Windows)

但是,当我尝试检查文件是否存在带有 root_path = 'C:/Users/Name/Desktop/ü' 之类的硬编码字符串时,我得到 "True"。

我使用 yaml.dump():

将数据(python 字典)转储到配置文件
with open(path_to_config, 'w', encoding='utf-8') as config:
    yaml.dump(data, config)

在文本编辑器中打开时看起来像这样:

destination:
  root_path: C:/Users/Name/Desktop/ü

将硬编码值打印到控制台显示:

C:/Users/Name/Desktop/▒

或使用 print(root_path.encode('utf-8')) 时:

b'C:/Users/Name/Desktop/\xc3\xbc.

要从我使用的配置文件中检索 root_path:

with open('config.yaml') as cfg:
    user_data = yaml.load(cfg)
    root_path = user_data['destination']['root_path']

当我打印从 config.yml 文件中检索到的 root_path 时,我得到:

C:/Users/Name/Desktop/ü

并使用 print(root_path.encode('utf-8')):

b'C:/Users/Name/Desktop/\xc3\x83\xc2\xbc'

这种差异从何而来,我如何转换从配置文件加载的值,以便 os.path.isdir() 可以找到该文件?

在大多数示例中,您会看到使用以下方法从光盘读取 YAML 文件:

yaml = ruamel.yaml.YAML()
with open('config.yaml') as fp:
    yaml.load(fp)

那个打开,就是打开阅读(和做open("config.yaml", "r")一样)。这在 Linux 或 Windows 上使用 ASCII/text 文件时很好。但是为了让 YAML 解析器正确处理 Windows 上的非 ASCII 输入,您应该以读取二进制模式打开文件:

yaml = ruamel.yaml.YAML()
with open('config.yaml', 'rb') as fp:
    yaml.load(fp)