小编Dav*_*d S的帖子

PyYAML 中 yaml.load 和 yaml.SafeLoader 的区别

这里是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")
Run Code Online (Sandbox Code Playgroud)

然后我在输出中看到 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'
Run Code Online (Sandbox Code Playgroud)

由于商业原因,我无法在此处发布实际的数据文件,但是有人对如何让 SafeLoader 工作有任何提示吗?

python yaml

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×1

yaml ×1