Search code examples
pythonpython-3.xrandom-access

How to check if file object is random access


I have a function that accepts an arbitrary file handle and either loads all the data or allows the data to be loaded lazily if the object supports 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))

How can I check if a file object supports random access?


Solution

  • You can use seekable method to check if the file supports random access.

    seekable()

    Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.