我想尝试这两个例子:
Parsing a YAML file in Python, and accessing the data?
但由于某种原因,我不断收到以下错误消息:
Traceback (most recent call last):
File "test.py", line 3, in <module>
doc = yaml.load(f)
File "/usr/local/lib/python2.7/dist-packages/yaml/__init__.py", line 71, in load
return loader.get_single_data()
File "/usr/local/lib/python2.7/dist-packages/yaml/constructor.py", line 37, in get_single_data
node = self.get_single_node()
File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 36, in get_single_node
document = self.compose_document()
File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 55, in compose_document
node = self.compose_node(None, None)
File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 133, in compose_mapping_node
item_value = self.compose_node(node, item_key)
File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 64, in compose_node
if self.check_event(AliasEvent):
File "/usr/local/lib/python2.7/dist-packages/yaml/parser.py", line 98, in check_event
self.current_event = self.state()
File "/usr/local/lib/python2.7/dist-packages/yaml/parser.py", line 449, in parse_block_mapping_value
if not self.check_token(KeyToken, ValueToken, BlockEndToken):
File "/usr/local/lib/python2.7/dist-packages/yaml/scanner.py", line 116, in check_token
self.fetch_more_tokens()
File "/usr/local/lib/python2.7/dist-packages/yaml/scanner.py", line 257, in fetch_more_tokens
% ch.encode('utf-8'), self.get_mark())
yaml.scanner.ScannerError: while scanning for the next token
found character '\t' that cannot start any token
in "tree.yaml", line 2, column 1
我通过执行以下操作安装了PyYAML:
python setup.py install
我还测试了它:
python setup.py test
似乎没问题。
现在授予我对Python和YAML有点新意,但我已经按照这两个字母的链接。我有一个名为tree.yaml的文件和一个名为test.py的文件,每个文件包含以下内容:
test.py
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
txt = doc["treeroot"]["branch1"]
print txt
tree.yaml
treeroot:
branch1: branch1 text
branch2: branch2 text
在你问之前,是的,我验证了我的标签空间,并通过验证器运行了YAML文件。知道为什么这不起作用吗?好像它无法与PyYAML通信。我再次对这一切都很陌生,所以我还不了解它是如何工作的以及如何整合所有这些。
感谢您的帮助!
我要回家过一天,所以将远离电脑一点点。将尽快回来或尝试通过电话回复/回答任何问题。
由于
答案 0 :(得分:1)
Yaml文件使用空格,而不是制表符作为缩进。在您提供的错误中,显然第二行中的第一个字符是标签。请用2或4个空格替换它,它应该可以工作。
标签不在yaml中,因为不同的编辑器和工具会对它们进行不同的处理。为了避免这种混乱,你应该使用空格。