【发布时间】:2021-05-07 02:38:57
【问题描述】:
我正在学习 yaml 文件并使用 pyyaml 解析它们,但遇到了一个我正在努力寻找解决方案的问题。基本上情况是这样的:我有两个不同格式的 .yaml 文件,虽然我可以访问文件中的子目录,但相同的语法不能访问第二个文件中的子目录。
这里有两个 .yaml 文件:
file1.yaml(来源:https://dev.to/developertharun/yaml-tutorial-using-yaml-with-python-pyyaml-443d):
---
username: Shiv
password: shiv@456
path:
- VLC Media Player: /etc/vlc
- Visual Studio Code: /etc/vscode
- Google Chrome: /etc/chrome
softwares:
s1:
- VLC Media Player
s2:
- Visual Studio Code
- Google Chrome
- Git Bash
- Video Convertor
- Node Js
这里是file2.yaml:
681:
activities:
copying:
time: 480
manufacturing:
materials:
- quantity: 86
typeID: 38
682:
activities:
copying:
time: 480
manufacturing:
materials:
- quantity: 133
typeID: 38
以下代码打开每个 .yaml 文件,打印整个 yaml 文件内容,并尝试分别打印第一个条目“用户名”和“681”
import yaml
# A function to read a .yaml file
def read_yaml(filename):
with open('%s'%filename) as f:
file = yaml.safe_load(f)
return file
# read first file, pretty print file contents,
# and print value of 'username' key:
file1 = read_yaml('file1.yaml')
pprint.pprint(file1)
print(file1['username'])
# read second file, pretty print file contents,
# and print value of '681' key:
file2 = read_yaml('file2.yaml')
pprint.pprint(file2)
print(file2['681'])
此代码在最后一行失败并给出 KeyError: '681'
所以,如您所见,pyyaml 可以加载上面的两个文件,但是在调用 file2 中的根字典时出现了问题。
任何帮助将不胜感激。
【问题讨论】:
-
你试过
681(整数而不是字符串)作为第二个文件的键吗?