Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip lines when reading a yaml file in python?

Tags:

python

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]

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.

like image 917
Aengus Avatar asked Dec 06 '22 23:12

Aengus


1 Answers

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]

Skipping the first 5 lines also works.

like image 140
mhawke Avatar answered Dec 10 '22 12:12

mhawke