python module using yaml

python: yaml module
a, yaml document describes
yaml is a specialized language used to write the configuration file.
1. yaml file rule

    case sensitive;
    use indention hierarchical relationship;
    using spacebar indent to indent rather than the Tab key
    number is not fixed indented spaces, only the left side elements of the same level alignment;
    characters in the document you need not be quoted string, but if string contains special characters need to use quotation marks;
    Note identified as #

2. YAML file data structure

    objects: a set of key-value pairs (the "map or dictionary")
    key-value pairs with colon ":" a structure represented, between the colon and the required space-separated values
    array: in sequence a set of values (referred to as "sequence or list")
    before the array plus - required space between symbols, the symbol value ' " partition
    scalar (scalars): individual, can not be divided value (eg: string, bool, integer, floating point number, time, date, etc. null)
    None null value can be represented by -

two, Python read yaml profile
1. prerequisite

before reading the file python yaml need to install and introducing PyYAML yaml module:

    used to install the module is yaml pyyaml (pip3 install pyyaml);
    imported modules is yaml (import yaml)

2. read ya ml data file

python open reading by way of the data file, then through the load function into a list or dictionary data;

Import yaml
Import OS

DEF get_yaml_data (yaml_file):
    # yaml File Open
    Print ( "Get *** *** yaml file data")
    = Open File (yaml_file, 'R & lt', encoding = "UTF-. 8")
    file_data = File.read ()
    File.close ()
    
    Print (file_data)
    Print ( "type:", type (file_data))

    # string into the dictionary or list of
    print ( "*** conversion dictionary or list data yaml ***")
    data = yaml.load (file_data)
    Print (data)
    Print ( "type:", type (data))
    return data
current_path os.path.abspath with = ( ".")
yaml_path = the os.path.join (current_path, "config.yaml")
get_yaml_data (yaml_path)

"""
*** *** get yaml file data
# Yaml key-value pair: i.e. the python dictionary
usr: My
PSW: 123 455
Type: <class 'STR'>
*** converted data as a dictionary or list yaml ***
{ 'usr': 'My', 'PSW': 123 455}
type: <class 'dict'>
"" "

3. YAML data file of key

(1) yaml file contents key-value pair:

# YAML key-value pair: i.e. the python dictionary
usr: My
PSW: 123455
s: "abc \ n"

data python parsed yaml acquired file:

{ 'usr': 'My', 'PSW': 123 455, 'S': 'ABC \ n-'}

(2) yaml file contents " key-value pair "nested" key of the "

# key nested yaml: i.e. nested dictionaries in python dictionary
USR1:
  name: a
  PSW: 123
USR2:
  name: B
  PSW: 456

python parses the acquired data file yaml : {

'USR1': { 'name': 'A ',' PSW ': 123},' USR2 ': {' name ':' B ',' PSW ':}} 456

(. 3) YAML file "key-value pair" nested "array"

# key YAML value pairs nested array
usr3:
  - A
  - B
  - C
USR4:
  - B

Get parsed yaml file python data:

{ 'usr3': [ 'A', 'B', 'C'], 'USR4': [ 'B']}

4. yaml file data array

(. 1) the contents of an array yaml file

# yaml array
- a
- B
-. 5

data acquired python yaml parses the file:

[ 'a', 'B',. 5]

(2) file yaml "array" nested "key on"

# yaml "array" nested "key-on"
- USR1: AAA
- PSW1: 111
  USR2: BBB
  PSW2: 222

data acquisition python parses yaml file:

[{ ' USR1 ':' AAA '}, {' PSW1 ': 111,' USR2 ':' BBB ',' PSW2 ': 222}]

5. the basic data types YAML file:

# scalar
s_val: name # string: { 's_val': 'name '}
spec_s_val: "name \ n-" special string #: {' spec_s_val ':' name \ n '
num_val: 31.14 # numbers: { 'num_val': 31.14}
bol_val: to true # Boolean value: { 'bol_val': True}
nul_val: null # null values: { 'nul_val': None}
nul_val1: ~ # null values: { ' nul_val1 ': None}
time_val: 2018-03-01t11: 33 is: 22.55-06: time value # 00: {' time_val ': A datetime.datetime (2018,. 3,. 1,. 17, 33 is, 22 is, 550000)}
date_val: # date 2019-01-10 values: { 'date_val': datetime.date (2019,. 1, 10)}

6. the file referenced yaml

yaml file contents

animal3: FISH & animal3
Test: * animal3

data read python

{ ' animal3 ':' fish ',' test ':' fish '}

three, Python yaml plurality of documents read
a plurality of documents 1. yaml a file, using the partition --- ways to segment

such as: data file yaml

# segmented yaml file more documents
---
animal1:dog
age: 2
---
animal2: CAT
Age: 3

2. python script to read multiple documents a method yaml file

python get load_all function when yaml need to use data to parse all of the document, and then the data object from which to read

# yaml file contains multiple document, the document data are acquired
DEF get_yaml_load_all (yaml_file):
    # file open yaml
    file open = (yaml_file, 'R & lt', encoding = "UTF-. 8")
    file_data = File.read ()
    File.close ()
    all_data = yaml.load_all (file_data)
    for Data in all_data:
        Print (Data)
current_path = os.path.abspath with ( ".")
yaml_path = the os.path.join (current_path, "config.yaml")
get_yaml_load_all (yaml_path)
"" " results
{ 'animal1': 'Dog', 'Age': 2}
{ 'animal2': 'CAT', 'Age':. 3}
"""

Four, python object generation yaml document
1. yaml introduced directly (i.e. Import yaml) generated document yaml

The method does not list or dictionary data converted by standard mode yaml yaml.dump (), will only generate the document data into yaml

# python the document object generation yaml
Import yaml
DEF generate_yaml_doc (yaml_file):
    py_object = { 'School' : 'Zhang',
                 'Students.': [ 'A', 'B']}
    File Open = (yaml_file, 'W', encoding = 'UTF-. 8')
    yaml.dump (py_object, File)
    File.close ()
= os.path.abspath with current_path ( ".")
yaml_path = the os.path.join (current_path, "generate.yaml")
generate_yaml_doc (yaml_path)
"" "results
School: Zhang
Students.: [A, B]
" ""

2 . yaml generated using standard methods of ruamel module yaml document

(1) using ruamel module yaml proviso

    use yaml modules need to be installed: ruamel.yaml (pip3 install ruamel.yaml);
    imported modules: from ruamel import yaml

(2)ruamel模块生成yaml文档

def generate_yaml_doc_ruamel(yaml_file):
    from ruamel import yaml
    py_object = {'school': 'zhang',
                 'students': ['a', 'b']}
    file = open(yaml_file, 'w', encoding='utf-8')
    yaml.dump(py_object, file, Dumper=yaml.RoundTripDumper)
    file.close()
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
generate_yaml_doc_ruamel(yaml_path)
"""结果
school: zhang
students:
- a
- b
"""    from ruamel import yamlDEF get_yaml_data_ruamel (yaml_file):# read through from ruamel import yaml yaml file
(3) ruamel module reads the document yaml




    file = open(yaml_file, 'r', encoding='utf-8')
    data = yaml.load(file.read(), Loader=yaml.Loader)
    file.close()
    print(data)
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "dict_config.yaml")
get_yaml_data_ruamel(yaml_path)

 

The Code

. 1  Import yaml
 2  Import OS
 . 3  
. 4  # single document 
. 5  DEF get_yaml_data (yaml_file):
 . 6      # Open yaml file 
. 7      Print ( " *** acquiring data file yam *** " )
 . 8      File Open = (yaml_file, ' R & lt ' , = encoding ' UTF-. 8 ' )
 . 9      file_data = File.read ()
 10      File.close ()
 . 11  
12 is      Print (file_data)
 13 is      Print ( " type ", type (file_data))
 14  
15      # to convert the string to a dictionary or list 
16      Print ( " *** conversion dictionary or list data yaml *** " )
 . 17      Data = yaml.safe_load (file_data)   # safe_load, safe_load, unsafe_load 
18 is      Print (Data)
 . 19      Print ( " type " , type (Data))
 20 is      return Data
 21 is  
22 is current_path = os.path.abspath with ( " . " )
 23 is yaml_path = the os.path.join (current_path, " config.yaml " )
 24 get_yaml_data (yaml_path)
 25  
26 is  
27  # YAML file when a plurality of documents containing, respectively acquire the document data 
28  DEF get_yaml_load_all (yaml_file):
 29      # open file 
30      File = Open (yaml_file, ' R & lt ' , encoding = ' UTF-. 8 ' )
 31 is      file_data = File.read ()
 32      File.close ()
 33 is  
34 is      all_data = yaml.full_load (file_data)
 35      for Data in all_data:
 36          Print ( ' Data ----- ' , Data)
37 
38 current_path=os.path.abspath(".")
39 yaml_path=os.path.join(current_path,"config.yaml")
40 get_yaml_load_all(yaml_path)
41 
42 
43 #生成yaml文档
44 def generate_yaml_doc(yaml_file):
45     py_ob={"school":"zhang",
46            "students":['a','b']}
47     file=open(yaml_file,'w',encoding='utf-8')
48     yaml.dump(py_ob,file)
49     file.close()
50 
51 current_path=os.path.abspath(".")
52 yaml_path=os.path.join(current_path,"generate.yaml")
53 generate_yaml_doc(yaml_path)

Results of the

 

 


Original: https: //www.jianshu.com/p/eaa1bf01b3a6

Guess you like

Origin www.cnblogs.com/lisa2016/p/11764808.html