utils.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:heaviside 作者: jhuapl-boss 项目源码 文件源码
def read(obj):
    """Context manager for reading data from multiple sources as a file object

    Args:
        obj (string|Path|file object): Data to read / read from
                                  If obj is a file object, this is just a pass through
                                  If obj is a Path object, this is similar to obj.open()
                                  If obj is a string, this creates a StringIO so
                                     the data can be read like a file object

    Returns:
        file object: File handle containing data
    """
    try: # Python 2 compatibility
        is_unicode = isinstance(obj, unicode)
    except NameError:
        is_unicode = False

    is_open = False
    if isinstance(obj, Path):
        fh = obj.open()
        is_open = True
    elif isinstance(obj, str) or is_unicode:
        fh = StringIO(obj)
        fh.name = '<string>'
    elif isinstance(obj, IOBase):
        fh = obj
    else:
        raise Exception("Unknown input type {}".format(type(obj).__name__))

    try:
        yield fh
    finally:
        if is_open:
            fh.close()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号