python: writing binary file

November 20th, 2008 mysurface Posted in python | Hits: 219608 | 46 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.

46 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

  32. Muuch before telemarketing campaigns can be embarked upon, call center experts start conducting
    market research. These things are generally inn complete opposife for esch other it would be comparable to
    seeking out a geeky athlete, not impossible but clearly a challenge.
    If you don’t have time to do a full-time course there are always
    seminars and workshops that you can skgn up for.

    My web-site; dark horse companies

  33. Examine the frame to see if there are any noticeable cracks, and lookk for huge portions witth rust.
    It can be as simple as pre-cooking and bringing a lasagna, complete with garlic bread, salad and wine.
    Aaron Anderson is passionate about writing on ceramic chef’s
    knife, ceramic chef, Kyocera chef knife and Kyocera Kyotop Damascus knife articles.

    my blog: best kitchen knife In the world

  34. It’s not my first time to pay a quick visit this site,
    i am visiting this site dailly annd obtain pleasant data
    from here daily.

    my blog Cloud pbn Review; Alphonso,

  35. Excellent post. I was checking constantly this blog and I’m impressed!
    Extremely helpful informatgion particularly the laast part :) I care for such information a lot.

    I wass seeking tis certain info for a very lng time.
    Thank you and good luck.

    My web siite ::Iris cover

  36. you’re actually a just right webmaster. The site loading pace is amazing.
    It sort of feels that you’re doing any unique trick. Also, The contents are masterpiece.

    you’ve performed a fantastic task on this subject!

    Take a look at my blog :: ice cream maker reviews (icecreammakers.edublogs.org)

  37. An outstanding share! I hafe just forrwarded this onto a colleague who
    hass been doing a little research on this. And he in fact ordersd me dinner simply because I discovered
    it for him… lol. So let mme reword this….
    Thanks for the meal!!But yeah, thahx ffor spending some time to
    talk about this subject here on your site.

    Here is my weblog – Hydroponic Equipment

  38. Wonderful post however I was wanting to
    know if yyou could writye a litt more on this topic? I’d bbe very thankful if youu could elaborate a little bit
    further. Kudos!

    Feel free to surf to my site: best vibration platform machines

  39. I all the time emailed this blog post pave to alll my contacts, because if
    like to read it then my friends will too.

    My web page – alcohol breath tester

  40. It’s actually a cool and helpfuhl piece of information. I am satisfied
    that you just shhared this helpful information with us.
    Pleasee stay uus informed loke this. Thannk you for sharing.

    My page: safari in dubai (Lon)

  41. Wonderful goods from you, man. I’ve understand your stuff previous to and you are just too excellent.
    I really like what you have acquired here, certainly like
    what you are stating and the way in which yyou say it. You make it enjoyable and
    you still take care of too keep it smart. I cant wait to
    read far more from you. This is actually a terrific site.

    Here is my web-site :: desert safari tours

  42. I don’t now if it’s just me or if perhaps everybody else experiencing issues wigh your website.

    It appears lke som of the text witrhin your posts are
    running off the screen. Caan someone else please provide feedback and let
    mme know if this is happening to them ass well?
    This may be a issue witfh mmy web browser because I’ve had this happen previously.
    Thank you

    My web ssite :: Manchester Emergency plumber

  43. Very rapiely this webb site will be famokus among all blogging aand site-building viewers, due to it’s
    pleasant articles

    Feeel free to visit my weblpg Best Cat Toys (German)

  44. I’m really enjoyiung the design and layout of your site.
    It’s a very easy on the eyes whicxh makes it mjch more pleasant for me to come here and
    visit more often. Did yyou hire out a designer to create your theme?
    Superb work!

    myweb page: vshicle wraps gta (Bridget)

  45. Hello there, You have done a fantastic job. I will certainly digg it and personally suggest to
    my friends. I’m confident they’ll be benefited from this website.

    Check outt my blog: Best Blwnders (Inherstilettos.Tumblr.Com)

  46. At this moment I amm going away to do my breakfast, when having myy breakast coming yet again to read other
    news.

    Here is myy websitge – Serrapeptase (Santiago)

Leave a Reply