这里是 Python 新手。
我安装了 PyYAML 并尝试使用我在网上发现的这段经过修改的代码来解析给我的 YAML 文件。
import yaml
if __name__ == '__main__':
try:
foo = open("foo.txt","a+")
except:
print("Error in opening file.")
stream = open("s.yaml", 'r')
dictionary = yaml.load(stream)
#dictionary = yaml.SafeLoader(stream)
for key, value in dictionary.items():
foo.write(key + " : " + str(value)+"\n")
然后我在输出中看到,由于安全问题,yaml.load 已被弃用。所以我尝试使用 SafeLoader 来运行它。但这给了我错误
Traceback (most recent call last):
File ".\parseYAML.py", line 11, in <module>
for key, value in dictionary.items():
AttributeError: 'SafeLoader' object has no attribute 'items'
出于商业原因,我不能在这里发布实际的数据文件,但是有人对我如何让 SafeLoader 工作有任何提示吗?
最佳答案
我们使用以下代码片段来展示一些使用 SafeLoader 的方法:(对于最简单的情况,最后一行可能是您最感兴趣的内容)
import yaml
env_variable_matcher = re.compile(r'<your custom pattern here>')
def env_variable_parser(loader, node):
'''
Parse a yaml value containing ${A-Z0-9_} as an environment variable
'''
...
return output
# Add support for yaml tag named env_var which matches a string containing
# an environment variable. The environment variable will be replaced with its value
yaml.add_implicit_resolver('!env_var', env_variable_matcher, Loader=yaml.SafeLoader)
yaml.add_constructor('!env_var', env_variable_parser, Loader=yaml.SafeLoader)
with open(config_file, 'r') as c_file:
config = yaml.safe_load(c_file)
关于python - PyYAML 中 yaml.load 和 yaml.SafeLoader 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434563/