python: writing binary file

November 20th, 2008 mysurface Posted in python | Hits: 311569 | 61 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:


Now, check it out with hexedit,

hexedit test.bin

You will see this:

00000000   5F 9D 3E                                                                                                _.>

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)

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

Isn’t it easy? I love python. You may want to discover more functions of binascii with ipython.

61 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…

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


  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. :)


    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.


    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:

    how can I get this ‘ff’ after.

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


    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

  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

  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.


  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 (

  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

    Here is myy websitge – Serrapeptase (Santiago)

  47. BARACK OBOLA and his LIBTARD henchmonkeys want the whole COUNTRY to get EBOLA!! It’s their PLAN to allow the MOOOOOOOZLIMS to take over and INSTITUTE sharia LAW!!!! No more AMERICA! No more FREEDOM AND LIBERTY!! No more BASEBALL APPLE PIE AND CHEVROLET!! NO more good old fashioned Wisconsin FISH BOILS! only SHARIA and burquas and MUZZORAMA.

  48. When someone writes an paragraph he/she retains the plan of a user in his/her brain that how a user can be aware of
    it. So that’s why this post is amazing. Thanks!

    Also visit mmy weblog: Explaindio

  49. Thank you, I have recently been searching for info about this topic for a while and
    yours is the best I have found out till now. However,
    what concerning the bottom line? Are you certain about the source?

    my pafe Greatness

  50. Thanks so much, I have been looking for a way to extract files which have been emeded in a image for a while now.

    now I can and have and inital success. thanks alot :)

  51. If you wish for to get much from this piece of writing then you have tto
    applyy thesee strategies to your won web site.

    My blog Plainfield painting services

  52. Pretty great post. I just stumbled upon your weblog and
    wanted to say that I have truly loved surfing around your
    weblog posts. After all I will be subscribing in your rss feed and I’m hoping you write once more very soon!

  53. Hi there, all is going sound here and ofcourse every one is sharing facts,
    that’s really fine, keep up writing.

  54. If you desire to improve your familiarity just keep visiting this site and be updated with
    the hottest gossip poste here.

    My web site list building

  55. With havin so much content do you ever run into any issues of plagorism or copyright violation? My site
    has a lot of unique content I’ve either created myself or outsourced but
    itt looks like a lot of it iis popping it up all over thee web without
    my agreement. Do you knjow any methods Shatter to Ejuice help prevent content from being ripped off?
    I’d definitely appreciate it.

  56. Good – I should definitely pronounce, impressed with your site. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your client to communicate. Nice task.

  57. Please let me know if you’re looking for a article writer for your
    weblog. You have some really good articles and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d love to
    write some content for your blog in exchange for a
    link back to mine. Please shoot me an email if interested.

  58. I hope that it’s acceptable that I write about this with just a few of my clients, this will
    help their comprehension of binary options trading significantly.

  59. You need to be a part of a contest for one of the best blogs on the internet.
    I most certainly will highly recommend this site!

  60. What i don’t understood is in reality how you’re now nott actually a lot more neatly-appreciated than you may be now.
    You are so intelligent. You understand thus significantly in relation to this
    matter, produuced me in my opinion believe it from so many
    various angles. Its like men and women aren’t fascinatedd until it’s
    something Migration to cloud; Lynda, do with Lady gaga!
    Your own stuffs outstanding. All the time handle it up!

  61. Lucretia Shea Says:


    SEO Link building is a process that requires a lot of time.
    If you aren’t using SEO software then you will know the amount of work load involved in creating accounts, confirming emails and submitting your contents to thousands of websites in proper time and completely automated.

    With THIS SOFTWARE the link submission process will be the easiest task and completely automated, you will be able to build unlimited number of links and increase traffic to your websites which will lead to a higher number of customers and much more sales for you.
    With the best user interface ever, you just need to have simple software knowledge and you will easily be able to make your own SEO link building campaigns.

    The best SEO software you will ever own, and we can confidently say that there is no other software on the market that can compete with such intelligent and fully automatic features.
    The friendly user interface, smart tools and the simplicity of the tasks are making THIS SOFTWARE the best tool on the market.


    Regards, Lucretia Shea
    France, CENTRE, Marignane, 13700, 25 Rue De La Pompe

Leave a Reply