首页 > 解决方案 > 如何在不执行复制的情况下将文件读入字节数组?

问题描述

我可以轻松地将文件读入bytearray使用:

with open('file.dat', 'rb') as f:
    data_readonly : bytes = f.read()
data = bytearray(data_readonly)

但是,调用bytearray执行复制。

如果我事先知道文件的大小,我可以使用:

SIZE = ...

data = bytearray(SIZE)
with open('file.dat', 'rb') as f:
    n_read = f.readinto(b)
assert n_read == SIZE

# data[:n_read] would perform a copy, which is what I was trying not to do!

事先不知道文件大小怎么办?

标签: pythonfile-io

解决方案


推荐阅读