Python YAML Methods

What is YAML ?

  • YAML (YAML Ain't Markup Language) is a human-readable data serialization language.
  • It is commonly used for configuration files
  • YAML file can be easily translated to multiple language types.

Translations from YAML tag to Python Object

YAML Tag Python Type
null None
bool bool
int int or long (Python 3 - int)
float float
binary str (Python 3 - bytes)
timestamp datetime
omap, pairs list of pairs
set set
str str or unicode (Python 3 - str)
seq list
map dict

Convert Python Object into YAML format

yaml.dump() function is used to convert the python object into YAML document.
if stream is specified in argument, serializes the python object into a given stream.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.dump([1, "two", 3.0]));                                             
Output:
$ python test_yaml.py
[1, two, 3.0]

Unicode strings in python object

Unicode string is converted as unicode string in YAML document also.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.dump([u'welcome', u'how r u?']));   
Output:
$ python test_yaml.py
[!!python/unicode 'welcome', !!python/unicode 'how r u?']
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print yaml.dump({'name': 'student1', 'dept': 'computer', 'marks': [87, 96]}); 
Output:
$ python test_yaml.py
dept: computer
marks: [87, 96]
name: student1

yaml.dump_all function

yaml.dump_all() function is used to convert the python objects into YAML documents. Each python object into separate YAML document.
if stream is specified in argument, serializes the python objects into a given stream as YAML documents.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.dump_all([1,2,3])); 
Output:
$ python test_yaml.py
1
--- 2
--- 3
...

yaml.safe_dump

safe_dump() function is used to convert the python object into YAML document. This function produces only standard YAML tags and cannot represent an arbitrary Python object.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.safe_dump([1., "two", 3.0]));  
Output:
$ python test_yaml.py
[1.0, two, 3.0]

Unicode strings in python object

if we use safe_dump function, unicode strings are converted into normal string in YAML document.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.safe_dump([u'welcome', u'how r u?']));   
Output:
$ python test_yaml.py
[welcome, 'how r u?']

default_flow_style argument

if default_flow_style argument is False, alignment of YAML document formated like below output.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.safe_dump([u'welcome', u'how r u?'], default_flow_style=False)); 
Output:
$ python test_yaml.py
- welcome
- how r u?
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print yaml.safe_dump({'name': 'student1', 'dept': 'computer', 'marks': [87, 96]}); 
Output:
$ python test_yaml.py
dept: computer
marks: [87, 96]
name: student1

#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.safe_dump_all([1,2,3])); 
Output:
$ python test_yaml.py
1
--- 2
--- 3
...

Python Object Serialization

Using yaml.dump function

Serializes python object into YAML format document file.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
f = open("file_name.txt", "w");                                                 
yaml.dump({'name': 'student1', 'dept': 'computer', 'marks': [87, 96]}, f);      
f.close();                                                                      
print("YAML serialization is done!"); 
Output:
$ python test_yaml.py
YAML serialization is done!
file_name.txt
$ cat file_name.txt 
dept: computer
marks: [87, 96]
name: student1

explicit_start argument

#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.dump([1,2,3], explicit_start=True));  
Output:
$ python test_yaml.py
--- [1, 2, 3]
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
print(yaml.dump_all([1,2,3], explicit_start=True)); 
Output:
$ python test_yaml.py
--- 1
--- 2
--- 3
...

Using yaml.safe_dump function

Serializes python object into YAML format document file.
safe_dump produces only standard YAML tags and cannot represent an arbitrary Python object.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
f = open("file_name.txt", "w");                                                 
yaml.safe_dump({'name': 'student1', 'dept': 'computer', 'marks': [87, 96]}, f);      
f.close();                                                                      
print("YAML serialization is done!"); 
Output:
$ python test_yaml.py
YAML serialization is done!
file_name.txt
$ cat file_name.txt 
dept: computer
marks: [87, 96]
name: student1

Convert YAML format into Python object

yaml.load converts a YAML document to a Python object.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
yaml_doc ="""                                                                   
- Python                                                                        
- Java                                                                          
- C                                                                             
- C#                                                                            
"""                                                                             
                                                                                
print(yaml.load(yaml_doc));  
Output:
$ python test_yaml.py
['Python', 'Java', 'C', 'C#']

Load multiple YAML documents

yaml.load_all function is used to load multiple YAML documents as python objects if string or file contails several YAML documents.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
yaml_doc ="""                                                                   
---                                                                             
name: Python                                                                    
description: python programming                                                 
---                                                                             
name: Java                                                                      
description: Java programming                                                   
---                                                                             
name: C                                                                         
description: C programming                                                      
"""                                                                             
                                                                                
                                                                                
for data in yaml.load_all(yaml_doc):                                            
    print data; 
Output:
$ python test_yaml.py
{'name': 'Python', 'description': 'python programming'}
{'name': 'Java', 'description': 'Java programming'}
{'name': 'C', 'description': 'C programming'}

Unicode string in YAML document

#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
yaml_doc ="""                                                                   
- !!python/unicode 'welcome'                                                    
- !!python/unicode 'how r u?'                                                   
"""                                                                             
                                                                                
                                                                                
print(yaml.load(yaml_doc));  
Output:
$ python test_yaml.py
[u'welcome', u'how r u?']

yaml.safe_load

  • Python object may be dangerous if you receive a YAML document from an untrusted source such as the Internet.
  • yaml.safe_load function is used to limit this ability to simple Python objects like integers or lists.
#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
yaml_doc ="""                                                                   
- python                                                                        
- yaml                                                                          
"""                                                                                                                                                       
print(yaml.safe_load(yaml_doc));  
Output:
$ python test_yaml.py
['python', 'yaml']

Python Object Deserialization

deserializes YAML document file into python object.

using yaml.load function

#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
f = open("file_name.txt", "r");                                                 
print(yaml.load(f));                                                            
f.close();   
Output:
$ python test_yaml.py
{'dept': 'computer', 'name': 'student1', 'marks': [87, 96]}

using yaml.safe_load function

#!/usr/bin/python                                                               
                                                                                
import yaml;                                                                    
                                                                                
f = open("file_name.txt", "r");                                                 
print(yaml.safe_load(f));                                                       
f.close();  
Output:
$ python test_yaml.py
{'dept': 'computer', 'name': 'student1', 'marks': [87, 96]}

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^