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()
评论列表
文章目录