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

标签 python python-3.x 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.

关于python - 如何检查文件对象是否是随机访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49376692/

相关文章:

python - 如何将 tensorflow 变量转换为 python 变量?

python - 将 sys.stdout 作为参数传递给进程

Python ctypes.string_at 释放行为

python-3.x - Groupby,转置和追加 Pandas ?

Python:类层次结构中的自定义深度复制

java - 有没有办法在 Android 中设置对加密数据的随机访问?

python - 根据百分位数绘制直方图

python - get() 接受 2 到 3 个位置参数,但给出了 4 个。为什么会出现这个错误?解决这个问题的办法是什么?

vb.net - 将 Quick BASIC 转换为 VB.Net - 随机访问文件

java - 随机访问文件 FileLock : java. io 与 java.nio