python: writing binary file

November 20th, 2008 mysurface Posted in python | Hits: 211474 | 31 Comments »

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.

31 Responses to “python: writing binary file”

  1. this is why i love open source :D hope opensource become over developed that microsoft will also become open source lol anyway visit this website it also offers free download of open source scripts such as PHP, java etc…

    http://www.zmartscript.co.cc

  2. How do I manipulate bytes before writing to a file? Say I want to add a random number between 0 and 255.

    Thanks
    MNM

  3. Thanks for this great article!

  4. Thanks! I was searching how to get images from a website, which haven’t got correct extensions… Using urllib, re and writing a binary file gives me quite useful effect. :)

  5. THANK YOU.

    I hope I can give back to the community by explain how this helped me with a problem. If this gets index by a search engine then someone will kill two birds with one stone.

    HOW TO RECOVER WEBPAGE FROM BROWSER CACHE

    I unwittingly lost an html template I was working on. I was able to recover the file from Google Chrome (you can also do this in Firefox in a similar way) by typing “about:cache” in the url. I then searched for the file; unfortunately the server gzips html to save bandwidth. All I had was rows of hex.

    Thankful, I found this article and pieced together the file, uncompressed it, and successfully recovered my file. Phew!

  6. Yes.. This is a simple tutorial how to write binary file in python. thx for sharing

  7. Thanks a lot this really helps!!

  8. Magnificent site. A lot of useful information here. I am sending it to several friends ans also sharing in delicious. And naturally, thanks in your effort!

  9. I do accept as true with all the concepts you have presented on your post. They’re very convincing and will definitely work. Still, the posts are too brief for beginners. May you please lengthen them a little from subsequent time? Thank you for the post.

  10. Great example, but how can I read the bytes.
    Some like this:
    file(‘test.txt’,'wb’).write(‘\xff’)

    how can I get this ‘ff’ after.

  11. I found a way to do what I say.
    It’s just this:

    f=file(‘test.txt’,'wb’)
    f.write(‘\xff’)
    f.close()

    print file(‘test.txt’,'rb’).read().encode(‘hex’)

    and the output is ‘ff’

  12. Greetings from Florida! I’m bored to death at work so I decided to browse your website on my iphone during lunch break. I enjoy the info you present here and can’t wait to take a look
    when I get home. I’m amazed at how quick your blog loaded on my mobile .. I’m not even
    using WIFI, just 3G .. Anyways, fantastic site!

  13. Pretty beneficial post. I just stumbled upon your blog and wanted to say that I have extremely enjoyed reading your blog posts. Any way I’ll be subscribing for your feed and I hope you article once more soon.

  14. Heya i am for the first time here. I came across this board and I
    find It really helpful & it helped me out a lot. I hope to present one thing back and help others such as you helped me.

  15. Way cool! Some very valid points! I appreciate you writing this post plus the rest
    of the site is also really good.

  16. Thanks for this post. i want to made my own file fuzzer, this is very useful for me. thanks once again!

  17. The bonus offers delend on deposits and include luxury watches,
    laptops, phones, short camcorders, desktopss aand big wheel Club membership.
    Its amazing with the purpose of World Finance hold known our
    achievements thank you. Well in that case we would be returned nothing in
    most instances.

  18. Conmsult your physiccian and nutritionist before starting any diewt
    orr fast. In addition, you’ll need to use either of the eating plans
    for women taalked about above – as you might also be a
    workling mom with kids. Those who are striving
    to reach the same goals are often a rich resource for
    each other.

  19. So, peope unhesitatingly are indulging themselves in
    used cars for sale throuhgh internet. Try tto ascertain whether the car has been repaired or
    rebuilt as a result of an accident as that will significantly affect its value.

    This actually worked out great for us, because
    I got a Carfax report to give to interested buyers.

  20. To get a FREE SEO Evaluation Report for your website, please ffill in your details below.
    Always keep this “Long Tail” keyword strategy in the back off your
    mid as you implement the following steps to achieve your own
    Top 10 Rankings iin Google. Rather than displaying 10 results per
    search query, in some cases onnly 7 are being
    shown.

  21. If you have a good appetite, youu can opt for an elaborate one.
    The architecture is amazing, the history behind the Temple of Heaven enthralling, easy to get to (unlike the
    Great Walls) and very photogenic. 1) Soak
    ried mushrooms in hot water for 20 minutes.

  22. Onne function of steroids is that it mimics the actions of naturally ocurring testosterone, resulting in the
    increase of protein levels, mushle buildup,
    and strength improvement. Isolated muscle exercises such as bicep curls cann be used too supplement your training program,
    but their benefits are minimal and should never replace an alternative such as the pull up.
    Net protein utilization iss a similar test to biological value (BV) except that it involves a direct measure of retention oof the absorbed
    nitrogen.

  23. Her daily menhu combined proteins like fish, chicken and meat,
    healthy fats like olive oil, avocados aand nuts, and fresh vegetables.
    Instead eat fresh fruit and vegetables, grains, lean meat and oily fish suh as mackerel.
    A Simple Guide To Getting Down To Your Goal Weight.

  24. This leads to a weakened immune system and the chances of you catching colds and viruses are increased immensely and letts not mention the greater chance of catching
    cancer. That way it will be easier to adapt annd the benefits you will experience will encouragee you to carry on. This
    is an unusual clubbing and it causes your body to react abruptly.

  25. Ovver the years, many of us have had a laugh at the expense of our paarents and grandparents in regard to their cherished “Back in my day” stories.
    It is difficult to learn when you can’t stay awake.
    Some people use food to stay in a low-grade stupor, safe from emotions on either extreme, and detachedd from the worldd just a little bit.

  26. This means that unlike the machines you usee at home, they will
    not lose consistency of the perfect stitching, even amidst long hours
    of work. If you talk to anyone who sews, they will let yyou
    know thatt thhe sewing machine is the perfect utilitarian invenjtion of the last 200
    years, by far. How do you make sense of
    all the brands, models and features.

  27. As they get older, keep teaching them little things.

    Learn to recognize each mentaal object, each thought, feeling and impulse, and rezpond to each with mindfulness
    and just seee it as it is. To expperience long-lasting passion in marriage, coupes must focus their sexual times together
    on delighting in each others bodies.

  28. Johnston has one off the most quickly growing communities in thee staate of Iowa.
    Thhe other gdeat ffeature about lijving in Tempe is how close youu are to the airport.
    Normally, real estate agents help their clients
    in preparing an offer.

  29. If one takes that information and multiplies it by the cost of an hour of
    electricity, they will know hhow much they will have to budtet to run each
    unit. That is one oof the main drawbacks oof central air
    conditioning. Then you can get a mobile air conditioner andd provide youhr stuff with a nice cool working atmosphere
    without violating your rental agreement.

  30. It haas a flat and wide-range frequency reslonse that delivers clean, clear and
    natural-sounding reproductioon of audio, regardless oof source.
    The most common speed ffor profezsional reel to reel recording.

    Moreover, tthe track productions can be done easily from your place.

    Review mmy web site; art scottsdale az

  31. I do not know if it’s just me or if perhaps everyone else experiencing issues with your site.
    It appears as if some of the written text within your posts are running off
    the screen. Can somebody else please comment and let
    me know if this is happening to them too? This could be a
    issue with my browser because I’ve had this happen before.

    Cheers

Leave a Reply