写入 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("x5Fx9Dx3E") 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 ="x45xF3" 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,现在要读一个二进制文件,查找doc只发现 file提供了一个read和write函数,而且读写的都是字符串,如果只是读写char等一个字节的还行,要想读写如int,double等多字节数 据就不方便了。在网上查到一篇贴子,使用struct模块里面的pack和unpack函数进行读写。下面就自己写代码验证一下。
接着再将其读进来
在操作过程中需要注意数据的size
注意 wb,rb中的b字,一定不可以少
方法1:
方法2
写入
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("x5Fx9Dx3E") 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 ="x45xF3" 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()