本文实例讲述了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字,一定不可以少
立即学习“Python免费学习笔记(深入)”;
本源码是我用过最好的淘客站源码。对于新站长很用帮助。重要!!注意上传完程序后要先登陆后台修改域名,否则会跳转到后台已设置的域名。 使用方法1:将文件夹里面的文件上传至您的空间根目录(不要在本地测试,本地测试期间功能将被限制,首页模板显示不正常!)2:访问网址http://您的网址/admin 账号:admin 密码:admin3:填写您基本网站信息,以及重要的淘客相关信息 声明:本程序使用权是本人
0
方法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("_>") 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 ="E" 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怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号