Files
Python_CookBook_repo/5.文件与IO/4.读写二进制数据.py
2025-09-10 16:12:45 +08:00

44 lines
1.1 KiB
Python
Raw Permalink 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.

from base64 import decode
def write_bin_file(bin_path):
with open(bin_path, 'wb') as f:
f.write(b'Hello BinFile')
if __name__ == "__main__":
path = "5.文件与IO/4.bin_file.bin"
write_bin_file(path)
# 如果想要打开二进制文件,那就需要做'rb'模式
with open(path, 'rb') as f:
print(f.read())
# 在打印的时候也有差异要记得先utf-8转码不然出来的是ascii
a = b'Hello BinFile'
for i in a:
print(i, end=' ')
print()
for i in a.decode('utf-8'):
print(i, end='')
print()
# C语言结构体和数组这种自带缓冲区接口的东西可以直接读写文件而不用先用encoder编码
import array
a = array.array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# 往文件里写array
with open(path, 'wb') as f:
f.write(a)
# 直接把bin array从文件里薅出来塞到b的缓冲区
b = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
with open(path, 'rb') as f:
f.readinto(b)
print(b)
# 但是这么干有风险,要谨慎应对