python读写二进制文件的方法

作者:守株待兔 时间:2023-04-30 15:28:41 

本文实例讲述了python读写二进制文件的方法。分享给大家供大家参考。具体如下:

初学python,现在要读一个二进制文件,查找doc只发现 file提供了一个read和write函数,而且读写的都是字符串,如果只是读写char等一个字节的还行,要想读写如int,double等多字节数 据就不方便了。在网上查到一篇贴子,使用struct模块里面的pack和unpack函数进行读写。下面就自己写代码验证一下。


>>> from struct import *
>>> file = open(r"c:/debug.txt", "wb")
>>> file.write(pack("idh", 12345, 67.89, 15))
>>> file.close()

接着再将其读进来


>>> file = open(r"c:/debug.txt", "rb")
>>> (a,b,c) = unpack("idh",file.read(8+8+2))
>>> a,b,c
(12345, 67.890000000000001, 15)
>>> print a,b,c
12345 67.89 15
>>> file.close()

在操作过程中需要注意数据的size

注意  wb,rb中的b字,一定不可以少

方法1:


myfile=open('c:\\t','rb')
s=myfile.read(1)
byte=ord(s) #将一个字节 读成一个数
print hex(byte) #转换成16进制的字符串

方法2


import struct
myfile=open('c:\\t','rb').read(1)
print struct.unpack('c',myfile)
print struct.unpack('b',myfile)

写入

To open a file for binary writing is easy, it is the same way you do for reading, just change the mode into “wb”.
file = open("test.bin","wb")
But, how to write the binary byte into the file?
You may write it straight away with hex code like this:
file.write("\x5F\x9D\x3E") file.close()
Now, check it out with hexedit,
hexedit test.bin
You will see this:
00000000 5F 9D 3E _.> 00000020 00000040
Now, open the file to append more bytes:
file = open("test.bin","ab")
What if I want to store by bin value into a stream and write it one short?
s ="\x45\xF3" s = s + "%c%c" % (0x45,0xF3) file.write(s) file.close()
Any convenient ways if I can obtained a hex string, and want to convert it back to binary format?
Yes, you just need to import binascii
import binascii hs="5B7F888489FEDA" hb=binascii.a2b_hex(hs) file.write(hb) file.close()

希望本文所述对大家的Python程序设计有所帮助。

标签:python,读写,文件
0
投稿

猜你喜欢

  • python 列表推导式使用详解

    2021-10-13 01:53:28
  • 在Ubuntu/Linux环境下使用MySQL开放/修改3306端口和开放访问权限

    2024-01-14 00:47:02
  • Python执行时间的几种计算方法

    2023-06-09 15:00:47
  • 在CentOS上配置Nginx+Gunicorn+Python+Flask环境的教程

    2021-09-04 07:31:23
  • SqlServer中的日期与时间函数

    2011-11-03 17:12:34
  • 用代码帮你了解Python基础(3)

    2021-03-20 07:22:46
  • tensorflow基于CNN实战mnist手写识别(小白必看)

    2021-01-26 22:33:42
  • 详解Go语言中new和make关键字的区别

    2024-05-21 10:19:20
  • 浅谈python for循环的巧妙运用(迭代、列表生成式)

    2023-04-15 02:17:29
  • 通过 for 循环比较 Python 与 Ruby 的编程区别

    2022-11-12 01:19:26
  • 运维角度浅谈MySQL数据库优化(李振良)

    2024-01-22 17:27:01
  • Python Matplotlib 实现3D绘图详解

    2022-06-20 15:47:03
  • asp 分页函数,可以显示 1,2,3,4,5... 前十页,后十页,下一页,上一页

    2009-07-05 18:34:00
  • tensorflow使用CNN分析mnist手写体数字数据集

    2021-07-20 20:29:35
  • MYSQL自定义函数判断是否正整数的实例代码

    2024-01-19 19:14:20
  • python 爬取哔哩哔哩up主信息和投稿视频

    2021-08-20 03:53:23
  • mysql5.7.19 winx64安装配置方法图文教程(win10)

    2024-01-20 20:12:45
  • 使用Python的networkx绘制精美网络图教程

    2022-10-31 06:52:47
  • javascript限制复选框的最大可选数

    2008-10-13 13:03:00
  • 对IPython交互模式下的退出方法详解

    2021-08-04 10:03:11
  • asp之家 网络编程 m.aspxhome.com