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,050 points
541 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,500 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,710 points
71 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,420 points
54 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 in Python by Waseem
• 2,830 points
12 views
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,710 points
1,097 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
67 views
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 in Python by Nymeria
• 3,500 points
49 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 in Python by Nymeria
• 3,500 points
48 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.