gpt4 book ai didi

python - YAML 加载器将路径视为十六进制数

转载 作者:行者123 更新时间:2023-12-04 04:19:39 24 4
gpt4 key购买 nike

我正在尝试在 Python 中读取 YAML 文件,但由于路径中的 '\' 将其视为十六进制数,因此失败,这是我的代码

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

我尝试用正斜杠和反斜杠给出路径。甚至尝试使用 os.path 但没有任何效果。相同的代码在 Mac 上运行良好,但在 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"

最佳答案

我在 Windows 上也遇到了这个问题。将我的字符串作为 r"<string>" 放在我的 YAML 文件中的建议对我不起作用。
相反,在我的 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'
相关部分来自 PyYAML docs :

Using single-quoted scalars, you may express any value that does not contain special characters. No escaping occurs for single-quoted scalars except that a pair of adjacent quotes '' is replaced with a lone single quote '.

Double-quoted is the most powerful style and the only style that can express any scalar value. Double-quoted scalars allow escaping. Using escaping sequences \x* and \u***, you may express any ASCII or Unicode character.


(这里的“标量”一词不像在数学课中那样指代数字。它的意思是单个值,而不是列表或字典。示例中的标量是路径,它们都是字符串。 )

关于python - YAML 加载器将路径视为十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59698041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com