如何检查文件对象是否是随机访问

How to check if file object is random access

我有一个函数可以接受任意文件句柄并加载所有数据或允许延迟加载数据如果对象支持随机访问。

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. If False, seek(), tell() and truncate() will raise OSError.

另一种符合 EAFP 的 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()
        try:
            # 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())
        except OSError:
            # Load the data up front if you can't
            self.headers[header.name] = (header, self.file.read(header.size))