Files
Python_CookBook_repo/5.文件与IO/9.将二进制数据读到可变缓冲区中.py
2025-09-10 16:12:45 +08:00

45 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os.path
import io
# 这是一个缓存区写入函数,目的是新建一个内存缓冲区,并把指定文件的内容写入
def read_info_buffer(filename):
# 建立一个字节数组缓冲区
buffer = bytearray(os.path.getsize(filename))
with open(filename, 'rb') as file:
file.readinto(buffer)
return buffer
if __name__ == '__main__':
# with open('5.文件与IO/9.bin_file.bin', 'wb') as f:
# f.write(b'Hello World')
# 将文件内容写入缓冲区
buf = read_info_buffer('5.文件与IO/9.bin_file.bin')
print(buf)
# 当然,缓冲区也可以有其他操作,比如切片
buf[0: 5] = b'hello'
print(buf)
# 当我们访问一个大文件时如果里面分为2个字节的多块就可以这样干
record_size = 2
buf2 = bytearray(record_size)
with open('5.文件与IO/9.bin_file.bin', 'rb') as f:
while True:
n = f.readinto(buf2)
print(buf2)
if n < record_size:
break
# 还有一个好玩的东西内存映像memoryview它允许我们直接操作对象的内存
suka = bytearray(b'suka blyet')
# 获取suka的内存地址
m = memoryview(suka)
# 将suka12~4位的地址给m2
m2 = m[1:4]
print(suka)
# 对这些地址上的数据进行相应长度的修改
m2[:] = b'abc'
# 可以看到这时候suka已经发生了变化
print(suka)