zoukankan      html  css  js  c++  java
  • Python读取二进制文件代码方法解析

    有二进制文件中保存了 20 亿个 2 Bytes 的数,需将其读出,每 20000 个数作图,拟合后输出结果。
    解决
    # -*- coding: utf-8 -*-
    """
    @author: kurrrr
    """
     
    import struct
     
    def main():
    data_file = open('run0035.bin', 'rb')
    data_temp = data_file.read(2)
    data_short, = struct.unpack('h', data_temp)
    print(data_short)
     
    if __name__ == '__main__':
    main()
     
    总结
    • open 时加上 b 关键词
    • read() 函数实现读取,参数为读取的字节数
    • 使用 struct 模块中的 unpack() 函数将二进制转化为十进制,注意 unpack() 函数返回的是 tuple,因此需要用 data_short, = struct.unpack(‘h', data_temp)
    关于 struct 模块中的 format 具体可在官网上找到。
    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
    每日分享,喜欢的看标题和多多点赞收藏加关注~~蟹蟹
  • 相关阅读:
    Ajax跨域解决实例
    关于tween.js测试介绍
    signal() 和 sigaction()
    信号概述
    监控文件事件
    栈和栈帧
    进程结构和内存布局
    关于文件I/o的原子操作
    查询Linux系统中glibc的版本
    IOPS和Throughput
  • 原文地址:https://www.cnblogs.com/nanhe/p/13639419.html
Copyright © 2011-2022 走看看