{"id":8343,"date":"2023-11-09T18:42:20","date_gmt":"2023-11-09T13:12:20","guid":{"rendered":"https:\/\/python-programs.com\/?p=8343"},"modified":"2023-11-10T12:24:59","modified_gmt":"2023-11-10T06:54:59","slug":"python-data-persistence-write-read-binary-file","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/","title":{"rendered":"Python Data Persistence – Write\/Read Binary File"},"content":{"rendered":"

Python Data Persistence – Write\/Read Binary File<\/h2>\n

When the mode parameter to open ( )<\/strong> function is set to \u2018w\u2019<\/strong> (or \u2018a\u2019) value, the file is prepared for writing data in text format. Hence write ( )<\/strong> and writelines ()<\/strong> methods send string data to the output file stream. The file is easily readable using any text editor. However, other computer files that represent pictures (.jpg), multimedia (.mp3, .mp4), executables (.exe, .com), databases (.db, .sqlite) will not be readable if opened using notepad like text editor because they contain data in binary format.<\/p>\n

Python\u2019s open( )<\/strong> function lets you write binary data to a file. You need to add \u2018b\u2019<\/strong> to the mode parameter. Set mode to \u2018wb\u2019<\/strong> to open a file for writing binary data. Naturally, such a file needs to be read by specifying \u2018rb\u2019<\/strong> as file opening mode.<\/p>\n

In the case of \u2018wb\u2019<\/strong> mode parameter, the write () method doesn\u2019t accept a string as an argument. Instead, it requires a bytes object. So, even if you are writing a string to a binary file, it needs to be converted to bytes first. The encode ( )<\/strong> method of string class converts a string to bytes using one of the defined encoding schemes, such as \u2018utf-8\u2019<\/strong> or \u2018utf-16\u2019.<\/strong><\/p>\n

Example<\/strong><\/p>\n

>>> f=open('binary.dat' , 'wb')\r\n>>> data='Hello Python'\r\n>>> encoded=data.encode(encoding='utf-16')\r\n>>> encoded\r\nb'\\xff\\xfeH\\x00e\\x001\\x001\\x00o\\x00 \\x00P\\x00y\\x00t\\ x00h\\x00o\\x00n\\x00'\r\n>>> f.write(encoded)\r\n26\r\n>>> f.close( )<\/pre>\n

To read back data from the binary files, the encoded strings will have to be decoded for them to be used normally, like printing it.<\/p>\n

Example<\/strong><\/p>\n

> > > f=open('binary.dat', 'rb')\r\n>>> encoded=f.read( )\r\n>>> data=encoded.decode(encoding='utf-16')\r\n>>> print (data)\r\nHello Python\r\n>>> f.close( )<\/pre>\n

If you have to write numeric data to a binary file, number object is first converted to bytes and then provided as argument to write() method<\/p>\n

Example<\/strong><\/p>\n

>>> f=open('binary.dat','wb')\r\n>>> num=1234\r\n>>> binl=num.to_bytes(16, 'big')\r\n>>> f.write(bin1)\r\n>>> f.close( )<\/pre>\n

To read integer data from binary file, it has to be extracted from bytes in the file.<\/p>\n

Example<\/strong><\/p>\n

>>> f=open( ' binary.dat' , 'rb')\r\n>>> data=f.read( )\r\n>>> num=int.from_bytes(data,'big')\r\n> > > num\r\n1234\r\n>>> f.close( )<\/pre>\n

In the to_bytes ()<\/strong> and from_bytes ()<\/strong> function, \u2018big\u2019<\/strong> is the value of the byte order parameter. Writing float data to a binary file is a little complicated. You\u2019ll need to use the built-in struct module and pack( )<\/strong> function from it to convert float to binary. Explanation of struct module is beyond the scope of this book.<\/p>\n

Example<\/strong><\/p>\n

>>> import struct\r\n> > > numl=1234.56\r\n>>> f=open('binary.dat','wb')\r\n>>> binfloat = struct .pack ('f ' num1)\r\n> > > f . write (binfloat)\r\n4\r\n> > > f.close ( )<\/pre>\n

To read back binary float data from file, use unpack () function.<\/p>\n

Example<\/strong><\/p>\n

>>> f=open('binary.dat','rb')\r\n>>> data=f.read( )\r\n>>> numl=struct.unpack('f', data)\r\n>>> print (num1)\r\n(1234.56005859375,)\r\n>>> f.close( )<\/pre>\n

 <\/p>\n","protected":false},"excerpt":{"rendered":"

Python Data Persistence – Write\/Read Binary File When the mode parameter to open ( ) function is set to \u2018w\u2019 (or \u2018a\u2019) value, the file is prepared for writing data in text format. Hence write ( ) and writelines () methods send string data to the output file stream. The file is easily readable using …<\/p>\n

Python Data Persistence – Write\/Read Binary File<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Data Persistence - Write\/Read Binary File - Python Programs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Data Persistence - Write\/Read Binary File - Python Programs\" \/>\n<meta property=\"og:description\" content=\"Python Data Persistence – Write\/Read Binary File When the mode parameter to open ( ) function is set to \u2018w\u2019 (or \u2018a\u2019) value, the file is prepared for writing data in text format. Hence write ( ) and writelines () methods send string data to the output file stream. The file is easily readable using … Python Data Persistence – Write\/Read Binary File Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Programs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/btechgeeks\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-09T13:12:20+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T06:54:59+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:site\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prasanna\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/python-programs.com\/#organization\",\"name\":\"BTech Geeks\",\"url\":\"https:\/\/python-programs.com\/\",\"sameAs\":[\"https:\/\/www.instagram.com\/btechgeeks\/\",\"https:\/\/www.linkedin.com\/in\/btechgeeks\",\"https:\/\/in.pinterest.com\/btechgeek\/\",\"https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg\",\"https:\/\/www.facebook.com\/btechgeeks\",\"https:\/\/twitter.com\/btech_geeks\"],\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"contentUrl\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"width\":350,\"height\":70,\"caption\":\"BTech Geeks\"},\"image\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/python-programs.com\/#website\",\"url\":\"https:\/\/python-programs.com\/\",\"name\":\"Python Programs\",\"description\":\"Python Programs with Examples, How To Guides on Python\",\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/python-programs.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage\",\"url\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/\",\"name\":\"Python Data Persistence - Write\/Read Binary File - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2023-11-09T13:12:20+00:00\",\"dateModified\":\"2023-11-10T06:54:59+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Data Persistence – Write\/Read Binary File\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\"},\"headline\":\"Python Data Persistence – Write\/Read Binary File\",\"datePublished\":\"2023-11-09T13:12:20+00:00\",\"dateModified\":\"2023-11-10T06:54:59+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage\"},\"wordCount\":356,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\",\"name\":\"Prasanna\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"caption\":\"Prasanna\"},\"url\":\"https:\/\/python-programs.com\/author\/prasanna\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Data Persistence - Write\/Read Binary File - Python Programs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/","og_locale":"en_US","og_type":"article","og_title":"Python Data Persistence - Write\/Read Binary File - Python Programs","og_description":"Python Data Persistence – Write\/Read Binary File When the mode parameter to open ( ) function is set to \u2018w\u2019 (or \u2018a\u2019) value, the file is prepared for writing data in text format. Hence write ( ) and writelines () methods send string data to the output file stream. The file is easily readable using … Python Data Persistence – Write\/Read Binary File Read More »","og_url":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2023-11-09T13:12:20+00:00","article_modified_time":"2023-11-10T06:54:59+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Prasanna","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/python-programs.com\/#organization","name":"BTech Geeks","url":"https:\/\/python-programs.com\/","sameAs":["https:\/\/www.instagram.com\/btechgeeks\/","https:\/\/www.linkedin.com\/in\/btechgeeks","https:\/\/in.pinterest.com\/btechgeek\/","https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg","https:\/\/www.facebook.com\/btechgeeks","https:\/\/twitter.com\/btech_geeks"],"logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/","url":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","contentUrl":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","width":350,"height":70,"caption":"BTech Geeks"},"image":{"@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/"}},{"@type":"WebSite","@id":"https:\/\/python-programs.com\/#website","url":"https:\/\/python-programs.com\/","name":"Python Programs","description":"Python Programs with Examples, How To Guides on Python","publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/python-programs.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage","url":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/","name":"Python Data Persistence - Write\/Read Binary File - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2023-11-09T13:12:20+00:00","dateModified":"2023-11-10T06:54:59+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"Python Data Persistence – Write\/Read Binary File"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb"},"headline":"Python Data Persistence – Write\/Read Binary File","datePublished":"2023-11-09T13:12:20+00:00","dateModified":"2023-11-10T06:54:59+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#webpage"},"wordCount":356,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/python-data-persistence-write-read-binary-file\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb","name":"Prasanna","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","caption":"Prasanna"},"url":"https:\/\/python-programs.com\/author\/prasanna\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8343"}],"collection":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=8343"}],"version-history":[{"count":2,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8343\/revisions"}],"predecessor-version":[{"id":9408,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8343\/revisions\/9408"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=8343"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=8343"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=8343"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}