How can I parse a YAML file in Python

0 votes
How can I parse a YAML file in Python? Was working on something, needed this!
Nov 21, 2018 in Python by Anirudh
• 2,090 points
10,477 views

1 answer to this question.

0 votes

Read & Write YAML files with Python 2+3 (and unicode)

# -*- coding: utf-8 -*-
import yaml
import io

# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
        'a string': 'bla',
        'another dict': {'foo': 'bar',
                         'key': 'value',
                         'the answer': 42}}

# Write YAML file
with io.open('data.yaml', 'w', encoding='utf8') as outfile:
    yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)

# Read YAML file
with open("data.yaml", 'r') as stream:
    data_loaded = yaml.load(stream)

print(data == data_loaded)

Created YAML file

a list:
- 1
- 42
- 3.141
- 1337
- help
- 
a string: bla
another dict:
  foo: bar
  key: value
  the answer: 42
answered Nov 21, 2018 by Nymeria
• 3,560 points

Related Questions In Python

+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,890 points
20,016 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
1,308 views
0 votes
0 answers

how can i read a text file in python?

can you specify the syntax and prequisites ...READ MORE

Apr 4, 2019 in Python by Waseem
• 4,540 points
585 views
+1 vote
1 answer

How can I delete a file in Python IDLE?

Hey @Starsarwar You have two different codes, they ...READ MORE

answered Oct 28, 2019 in Python by Kalgi
• 52,350 points
2,471 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,442 views
0 votes
1 answer
0 votes
1 answer

How can I read numbers in Python from a custom file?

Hi, good question. Let us first assume that ...READ MORE

answered Feb 6, 2019 in Python by Nymeria
• 3,560 points
1,136 views
0 votes
1 answer

How can I lookup hostname using the IP address with a timeout in Python?

Good question. I actually was stuck with ...READ MORE

answered Feb 6, 2019 in Python by Nymeria
• 3,560 points
2,571 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP