python-如何检查文件对象是否为随机访问
作者:互联网
我有一个接受任意文件句柄的函数,或者加载所有数据,或者如果对象支持随机访问,则允许延迟加载数据.
class DataLoader: def __init__(self, file): self.file = file self.headers = {} def load_data(self): # header is a hashable (e.g. namedtuple with name, size, offset) header = self.load_next_header() if self.file.random_access: # Return and load the data only as necessary if you can self.headers[header.name] = (header, None) self.file.seek(header.size + self.file.tell()) else: # Load the data up front if you can't self.headers[header.name] = (header, self.file.read(header.size))
如何检查文件对象是否支持随机访问?
解决方法:
您可以使用seekable
方法来检查文件是否支持随机访问.
seekable()
Return
True
if the stream supports random access. IfFalse
,seek()
,tell()
andtruncate()
will raiseOSError
.
标签:random-access,python-3-x,python 来源: https://codeday.me/bug/20191025/1927486.html