python: writing binary file
November 20th, 2008 mysurface Posted in python | Hits: 10784 |
Python is the best scripting language which I found it out perform Bash script as well as Lua. I like python’s scripting syntax, which is make sense and very convenient in string manipulations. Its now come to binary format manipulation, how convenient is python?
I have carry out some research on python into writing binary files. Either writing byte by byte manually, construct a binary stream then write it one short, or convert it from hex string, they are easy to write in python.
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()
Isn’t it easy? I love python. You may want to discover more functions of binascii with ipython.
Live Chat!









Leave a Reply