如何解析Python中读取二进制文件的代码实现?

2026-05-22 00:371阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计344个文字,预计阅读时间需要2分钟。

如何解析Python中读取二进制文件的代码实现?

问题:在二进制文件中保存了20亿个2Bytes的数据,需要将其读取出来,每20000个数作图,模拟输出结果。

解决方法:

1.读取二进制文件,逐个读取2Bytes的数据。

2.将读取的数据转换为整数。

如何解析Python中读取二进制文件的代码实现?

3.每20000个数存储到一个列表中。

4.使用绘图库(如matplotlib)对每个列表中的数据进行绘图。

5.输出绘图结果。

问题

有二进制文件中保存了 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 具体可在官网上找到。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计344个文字,预计阅读时间需要2分钟。

如何解析Python中读取二进制文件的代码实现?

问题:在二进制文件中保存了20亿个2Bytes的数据,需要将其读取出来,每20000个数作图,模拟输出结果。

解决方法:

1.读取二进制文件,逐个读取2Bytes的数据。

2.将读取的数据转换为整数。

如何解析Python中读取二进制文件的代码实现?

3.每20000个数存储到一个列表中。

4.使用绘图库(如matplotlib)对每个列表中的数据进行绘图。

5.输出绘图结果。

问题

有二进制文件中保存了 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 具体可在官网上找到。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。