python读取二进制

import struct
import os
# 文件头长度
# header_length = 24


def read_and_save_bx_csv(echo, csv):
    """
    Read a fcd file and save it as a bx csv file.
    :param fcd: 输入文件
    :param csv: 输出文件
    :return:
    """
    # f = open(echo, 'rb')
    # f.seek(0, 2)
    # 第一个参数表示偏移量(正数表示向后移动,负数表示向前移动),
    # 第二个参数表示位置(0--文件开头,1--当前位置,2--文件末尾)
    # seek(0, 2)表示移到与末尾相差0的位置,也就是末尾的位置

    # eof = f.tell()  # 得到文件末尾的数值


    with open(echo, 'rb') as r, open(csv, 'w') as w:
        # 忽略文件头
#file.seek()方法标准格式是:file.seek(offset,whence)
# offset:开始的偏移量,也就是代表需要移动偏移的字节数
# whence:给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。whence值为空没设置时会默认为0。
#         r.seek(header_length)

        r.seek(0, 2)
        eof = r.tell()
        r.seek(0,0)  #移到文件头

        while True:
                data = r.read(4)
                test_ID = int.from_bytes(data, byteorder='little', signed=False)
                data = r.read(4)
                gates = int.from_bytes(data, byteorder='little')
                data = r.read(4)
                depth = int.from_bytes(data, byteorder='little')
                data = r.read(4)
                Aid = int.from_bytes(data, byteorder='little')
                data = r.read(4)
                amplitude = int.from_bytes(data, byteorder='little')
                data = r.read(4)
                threshold = int.from_bytes(data, byteorder='little')
                w.write(f'{test_ID},{gates},{Aid},{depth},{Aid},{amplitude},{threshold}\n')
                if r.tell() >= eof:  # 将当前位置与文件尾(eof)比较
                  break
        r.close()




if __name__ == '__main__':
    # file_name = 'F:/dFile/1.echo'
    file_name = 'F:/dFile/1.echo'
    # bx_csv_name = 'F:/test csv/bx.csv'
    bx_csv_name = 'F:/test csv/bx.csv'
    read_and_save_bx_csv(file_name, bx_csv_name)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值