Загрузчик YAML рассматривает путь как шестнадцатеричное число - PullRequest
0 голосов
/ 11 января 2020

Я пытаюсь прочитать файл YAML в Python, но из-за '\' в пути он считает, что это шестнадцатеричное число и, следовательно, не удается, вот мой код

import yaml

def parse_yaml(file_path):
    with open(file_path) as stream:
        yaml_dict = None
        try:
            yaml_dict = yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)
    return yaml_dict


file_path = r"C:\\Users\\user\\PycharmProjects\\testautomation\\conf_windows\\generic_configs.yml"
print(parse_yaml(file_path))

Сообщение об ошибке:

Error

while scanning a double-quoted scalar
  in "C:\\Users\\user\\PycharmProjects\\testautomation\\conf_windows\\generic_configs.yml", line 2, column 16
expected escape sequence of 8 hexdecimal numbers, but found 's'
  in "C:\\Users\\user\\PycharmProjects\\testautomation\\conf_windows\\generic_configs.yml", line 2, column 21
None

Я попытался указать путь в прямом sla sh и в обратном sla sh. Даже пытался использовать os.path, но ничего не получалось. Тот же код работает нормально на Ma c, но не работает на Windows.

Содержимое файла yaml

batchwrite:
  input_file : "/Users/user/Documents/Codes/testautomation/input/batch_write_input.xlsx"
  output_path : "/Users/user/Documents/Codes/testautomation/output"
  dml_file : "/Users/user/Documents/Codes/testautomation/conf/info.dml"
  file_type_yml : "/Users/user/Documents/Codes/testautomation/conf/fields.yml"

1 Ответ

0 голосов
/ 12 января 2020

Ошибка относилась к пути, который я указал в файле YAML, а не к пути, который я дал коду. После добавления r "..." к строковому содержимому в YAML это сработало как шарм. Обновлено содержимое файла YAML

batchwrite:
  input_file : r"/Users/user/Documents/Codes/testautomation/input/batch_write_input.xlsx"
  output_path : r"/Users/user/Documents/Codes/testautomation/output"
  dml_file : r"/Users/user/Documents/Codes/testautomation/conf/info.dml"
  file_type_yml : r"/Users/user/Documents/Codes/testautomation/conf/fields.yml"
...