The example in this article describes how Python reads and writes binary files. Share to everyone for your reference. Specifically as follows:
Beginners Python, now read a binary file, find doc only found that file provides a read and write functions, and read and write is a string, if only read and write char and so on a byte of the row, to read and write such as int,double data such as multibyte is inconvenient. Find a post on the Internet, use the pack and unpack function inside the struct module to read and write. Write the code to verify the following.
|1 2 3 4||>>> from struct import * >>> file = open (r "C:/debug.txt", "WB") >>> File.write (Pack ("IDH", 1234 5, 67.89) >>> file.close ()|
And then read it in.
|1 2 3 4 5 6 7||>>> file = open (r "C:/debug.txt", "RB") >>> (a,b,c) = Unpack ("Idh", File.read (8+8+2)) >>> a,b,c (12345, 67.890000000000001) >>> print a,b,c 12345 67.89 >>> file.close ()|
You need to be aware of the size of the data during the operation
Note that the B word in wb,rb, must not be less
|1 2 3 4||Myfile=open (' c:t ', ' RB ') S=myfile.read (1) byte=ord (s) #将一个字节 read as a number of print hex (byte) #转换成16进制的字符串|
|1 2 3 4||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 are easy and it is the same way your do for reading and just change the ' mode into ' WB '.
File = Open ("Test.bin", "WB")
But, how do I write the binary byte into the file?
You could write it straight away with hex code like this:
File.write ("x5fx9dx3e") File.close ()
Now, the check it out with HexEdit,
You'll be here:
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, just need to import binascii
Import binascii hs= "5b7f888489feda" Hb=binascii.a2b_hex (HS) File.write (HB) File.close ()
I hope this article will help you with your Python programming.