在python中读取yaml文件时如何跳过行? [英] How to skip lines when reading a yaml file in python?

查看:46
本文介绍了在python中读取yaml文件时如何跳过行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉类似的问题,但它们似乎没有解决应该是简单的问题.我正在使用 Python 2.7x 并尝试读取与此类似的 YAML 文件:

I'm familiar with similar questions, but they don't seem to address what should be a simple problem. I am using Python 2.7x and trying to read a YAML file that looks similar to this:

%YAML:1.0
radarData: !!opencv-matrix
rows: 5
cols: 2
dt: u
data: [0, 0, 0, 0, 0, 10, 5, 3, 1, 22]

现在我只需要 'data:' 文档.我尝试了一种香草方法,然后尝试强制跳过前 4 行(第二个代码片段被注释掉).两种方法都会出错.

For now I only need the 'data:' document. I have tried a vanilla approach and then tried to force skip the first 4 lines (second code snippet that is commented out). Both approaches gave errors.

import yaml
stream = file('test_0x.yml', 'r') 
yaml.load(stream)
# alternative code snippet
# with open('test_0x.yml') as f:
#  stream = f.readlines()[4:]
# yaml.load(stream)

关于如何跳过前几行的任何建议将不胜感激.

Any suggestions about how skip the first few lines would be very appreciated.

推荐答案

其实你只需要跳过前两行.

Actually, you only need to skip the first 2 lines.

import yaml

skip_lines = 2
with open('test_0x.yml') as infile:
    for i in range(skip_lines):
        _ = infile.readline()
    data = yaml.load(infile)

>>> data
{'dt': 'u', 'rows': 5, 'data': [0, 0, 0, 0, 0, 10, 5, 3, 1, 22], 'cols': 2}
>>> data['data']
[0, 0, 0, 0, 0, 10, 5, 3, 1, 22]

跳过前 5 行也有效.

Skipping the first 5 lines also works.

这篇关于在python中读取yaml文件时如何跳过行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆