python二进制读写及特殊码同步
python对二进制文件的操作需要使用bytes类,直接写入整数是不行的,如果试图使用f.write(123)向文件中以二进制写入123,结果提示参数不是bytes类型。
import os import struct a = 0x1A2B3C4D b = 0x239875ad3d5ffaaa filepath = 'D:\\wygDocument\\python\\code\\abc.dat' f_in = open(filepath,'wb+') for value in range(1,5): f_in.write(struct.pack('>I',a)) f_in.write(struct.pack('>Q',b)) f_in.close() print('Write OK')
1 import os 2 import struct 3 4 #Read file into list 5 with open('E:/fep/tj19.txt','r') as f: 6 line = f.read().strip() 7 linestr = line.split('\n') #splited by line breaks 8 #linestr = line.split(r"[\s\n]",line) #splited by Space character and line breaks 9 10 f_out = open('E:/fep/realData.dat','xb') 11 12 frame_flag_0 = 0x1A2B3C4D5E6F 13 mask = 0xFFFFFFFFFFFF 14 15 for i in range(0,len(linestr)): 16 filepath = 'E:/fep/19/' + linestr[i] 17 f_in = open(filepath,'rb') 18 f_size = os.path.getsize(filepath) 19 f_in.seek(109) 20 21 offset = 109 22 chunk = 905 23 24 while True: 25 if offset >= f_size: 26 break 27 buff = f_in.read(15) 28 offset += chunk 29 30 unpacked_data = struct.unpack_from('>ih',buff,9) #start from the 9th byte 31 if(unpacked_data[0] != 439041101) or (unpacked_data[1] != 24175) #1A2B3C4D 5E6F 32 f_out.write(buff) 33 f_out.write(f_in.read(890)) # 9 + 6 + 890 34 35 f_in.seek(offset) 36 37 f_in.close() 38 f_out.flush() 39 40 f_out.close() 41 print('OK')
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步