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) # 但是这么干有风险,要谨慎应对