python - 如何在不执行复制的情况下将文件读入字节数组?
问题描述
我可以轻松地将文件读入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!
事先不知道文件大小怎么办?
解决方案
推荐阅读
- file - 在 AIX 中移动只有 2 行的文件
- vue.js - Laravel 8 和 Vue Js 页面 vue 模板不显示
- java - 如何使用 Java lambda 和流迭代 MultipartFile 数组
- c# - 如何使用 SurfaceViewRenderer 通过 Android 自定义渲染器实现访问远程 WebRTC 视频轨道的纵横比?
- reactjs - 从映射 React Router 中的对象动态构建路由的问题
- ios - DispatchQueue 的行为不像串行队列
- java - Java:“新字符串(旧字符串)”是否必要?(String 是引用还是值?)
- prometheus - 在 Grafana 中对 ad hoc 过滤器执行变量链接
- blazor - Blazor WASM 文件不存在(但可读吗?)
- sdn - 如何在 POX 控制器中添加流规则