zoukankan      html  css  js  c++  java
  • 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('
    ')  #splited by line breaks
     8   #linestr = line.split(r"[s
    ]",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')
  • 相关阅读:
    c++中stl函数的使用
    java 中String类的常见方法和StringBuffer类的使用
    c++模板类和模板函数
    c++简单工厂类的设计模式
    Android自定义的button按钮
    c++基类与派生类之间的转换
    Unity和Android结合出现Unabled to convert class into dex format
    jz2240用tftp下载程序步骤
    解决jz2440不能ping同主机问题
    android中的事件传递机制
  • 原文地址:https://www.cnblogs.com/mikew/p/11650659.html
Copyright © 2011-2022 走看看