python yaml 文件解析及str、repr函数的说明

记录说明 yaml 文件解析的方法及str、repr函数的区别

1. yaml 文件解析

config.yml

site_name: AJPy
pages:
  - Introduction: index.md
  - AJP overview: ajp.md
theme: readthedocs
code: 中文

解析yaml 文件

import yaml
import os


class OperateYaml(object):
    """
    操作yaml 文件
    """
    def __init__(self):
        pass

    def load_yaml_file(self, yaml_file_path):
        """
        加载 yaml 文件
        :param yaml_file_path:
        :return:
        """
        if not os.path.exists(yaml_file_path):
            print 'yaml file is not exist.'
            return
        if not os.path.splitext(yaml_file_path)[-1] == '.yml':
            print 'input file is not a yaml file'
            return
        with open(yaml_file_path) as fp:
            result = yaml.load(fp)
            # TODO 若yml 文件中含有中文, 使用以下方法进行转换
            result = repr(result).decode('unicode_escape')
        return result

    def write_dict_to_yaml_file(self, a_dict, output_path):
        """
        将字典内容序列化到 yaml 文件中
        :param a_dict:   待序列化的字典
        :param output_path:  输出文件路径
        :return:
        """
        if not isinstance(a_dict, dict):
            print 'must be input a dict.'
            return
        if not os.path.exists(output_path):
            os.makedirs(output_path)
        output_file_path = os.path.join(output_path, 'temp.yml')
        # 使用'a' ,当文件不存在时,创建一个新文件
        with open(output_file_path, 'a') as fp:
            yaml.dump(a_dict, fp, indent=4)


if __name__ == '__main__':
    oy = OperateYaml()
    # {'theme': 'readthedocs', 'code': u'中文', 'site_name': 'AJPy', 'pages': [{'Introduction': 'index.md'}, {'AJP overview': 'ajp.md'}]}
    print oy.load_yaml_file('config.yml')

    a_dict = {'topic': 'python', 'foo': ['foo1', 'foo2', 'foo3'], 'bar': {'bar1': 'value1', 'bar2': 'value2'}}
    oy.write_dict_to_yaml_file(a_dict, './result')

2. str() 和 repr() 函数的区别说明

Python 中将某一类型的 变量 或者 常量 转换为字符串对象通常有两种方法,str() 或者 repr().

  • str() 和 repr() 两个函数的 相同点 在于,都可以将任意的值转化为字符串

  • str() 和 repr() 的不同点在于:

    • 函数str()将其转化成为适于人阅读的前端样式文本, 输出追求可读性,输出格式要便于理解,适合用于输出内容到用户终端

    • repr(object)就是原本未处理的用于编译器阅读的后台底层代码, 输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用

>>> print(str('123'))       
123                         
>>> print(str(123))         
123                         
>>> print(repr('123'))      
'123'                       
>>> print(repr(123))        
123   
当把一个字符串传给str()函数再打印到终端的时候,输出的字符不带引号
而将一个字符串传给repr()函数再打印到终端的时候,输出的字符带有引号
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(str(now))
2020-02-22 15:41:33.012917
>>> print(repr(now))
datetime.datetime(2020, 2, 22, 15, 41, 33, 12917)
通过str()的输出结果能知道 now 实例的内容,但是却丢失了 now 实例的数据类型信息。
通过repr()的输出结果不仅能获得 now 实例的内容,还能知道 now 是datetime.datetime对象的实例
种一棵树最好的时间是十年前,其次是现在!
原文地址:https://www.cnblogs.com/gaozhidao/p/12350054.html