开发者社区> 问答> 正文

为什么可以使用相同的函数从字符串和文件处理程序中读取YAML数据?

我需要一次从文件中读取YAML数据,另一次从字符串中读取。令我惊讶的是,两者可以使用相同的函数:

import yaml

data = """

hello:

world

"""

doc = yaml.safe_load(data)

print(doc)

with open("data.yaml", 'w') as f:

f.write(data)

with open("data.yaml", 'r') as f:

doc = yaml.safe_load(f)

print(doc)

输出:

{'hello': 'world'}

{'hello': 'world'}

为什么会这样呢?

展开
收起
游客6qcs5bpxssri2 2019-10-12 11:00:55 2684 0
1 条回答
写回答
取消 提交回答
  • 这是Reader的代码: class Reader(object):

    def __init__(self, stream):
    
        if isinstance(stream, str):
    
            self.name = "<unicode string>"
    
            self.check_printable(stream)
    
            self.buffer = stream+'\0'
    
        elif isinstance(stream, bytes):
    
            self.name = "<byte string>"
    
            self.raw_buffer = stream
    
            self.determine_encoding()
    
        else:
    
            self.stream = stream
    
            self.name = getattr(stream, 'name', "<file>")
    
            self.eof = False
    
            self.raw_buffer = None
    
            self.determine_encoding()
    

    函数本身会检验数据类型然后做不同的处理。

    2019-10-12 11:02:28
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载