{"id":585,"date":"2017-01-21T16:04:40","date_gmt":"2017-01-21T08:04:40","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=585"},"modified":"2018-09-05T00:19:28","modified_gmt":"2018-09-04T16:19:28","slug":"how-to-save-and-load-objects-to-and-from-file-in-python-via-facilities-from-the-pickle-module","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-save-and-load-objects-to-and-from-file-in-python-via-facilities-from-the-pickle-module\/","title":{"rendered":"How to save and load objects to and from file in Python via facilities from the pickle module"},"content":{"rendered":"<p>There are times when it is more convenient for us to choose object serialization over database management systems for the persistency of the data that our Python scripts work with.  <\/p>\n<p>In this post, I document how we can save and load objects to and from file in Python using facilities from the pickle module.<\/p>\n<h2>Saving objects to file in Python<\/h2>\n<p>To save objects to file in Python, we typically go through the following steps:<\/p>\n<ol>\n<li>Import the <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html\" target=\"_blank\">pickle module<\/a>.<\/li>\n<li>Get a file handle in write mode that points to a file path.<\/li>\n<li>Use <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html#pickle.dump\" target=\"_blank\"><code>pickle.dump<\/code><\/a> to write the object that we want to save to file via that file handle.<\/li>\n<\/ol>\n<p>With these steps in mind, let's us create a Python script, <code>save_dictionary_to_file.py<\/code>, with the following Python codes:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Step 1\r\nimport pickle\r\n\r\nconfig_dictionary = {'remote_hostname': 'google.com', 'remote_port': 80}\r\n\r\n# Step 2\r\nwith open('config.dictionary', 'wb') as config_dictionary_file:\r\n\r\n  # Step 3\r\n  pickle.dump(config_dictionary, config_dictionary_file)\r\n<\/pre>\n<p>In step 1, we import the pickle module with the <code>import<\/code> keyword. <\/p>\n<p>In step 2, we use the <code>with<\/code> keyword and the <a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#open\" target=\"_blank\">open<\/a> function to create a file handle that points to <code>config.dictionary<\/code> in the same directory where we will run <code>save_dictionary_to_file.py<\/code>. <\/p>\n<p>The first string that we supply to the <code>open<\/code> function denotes the filepath to write our dictionary of values. The second string that we supply to the open function indicates that we want a file handle that writes binary contents to the file.<\/p>\n<p>The <code>with<\/code> keyword ensures that the file handle generated by the <code>open<\/code> function is closed after our dictionary is serialized to file.<\/p>\n<p>Finally in step 3, we use the <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html#pickle.dump\" target=\"_blank\"><code>pickle.dump<\/code><\/a> function to write the contents of our dictionary to a file that will be named as <code>config.dictionary<\/code>.<\/p>\n<p>After running <code>save_dictionary_to_file.py<\/code>, we should be able to see the config.dictionary file in the same directory where we run our Python script. <\/p>\n<h2>Loading objects from file in Python<\/h2>\n<p>To load the object from file in Python, we typically go through the following steps:<\/p>\n<ol>\n<li>Import the <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html\" target=\"_blank\">pickle module<\/a>.<\/li>\n<li>Get a file handle in read mode that points to a file path that has a file that contains the serialized form of a Python object.<\/li>\n<li>Use <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html#pickle.load\" target=\"_blank\"><code>pickle.load<\/code><\/a> to read the object from the file that contains the serialized form of a Python object via the file handle.<\/li>\n<\/ol>\n<p>With these steps in mind, let us create a Python script, <code>load_dictionary_from_file.py<\/code> with the following Python codes:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Step 1\r\nimport pickle\r\n\r\n# Step 2\r\nwith open('config.dictionary', 'rb') as config_dictionary_file:\r\n\r\n    # Step 3\r\n    config_dictionary = pickle.load(config_dictionary_file)\r\n\r\n    # After config_dictionary is read from file\r\n    print(config_dictionary)\r\n<\/pre>\n<p>Similar to writing the dictionary to file, we import the pickle module in step 1.<\/p>\n<p>In step 2, we use the <code>with<\/code> keyword with the open function to get a file handle that points to <code>config.dictionary<\/code> in the same directory where we will run <code>load_dictionary_from_file.py<\/code>. <\/p>\n<p>As with saving the dictionary to file, we supply <code>config.dictionary<\/code> as the first input to the <code>open<\/code> function to indicate the file path to the file which contains the serialized dictionary. This time round, we supply the string <strong>'rb'<\/strong> instead of <strong>'wb'<\/strong> to indicate that we want a file handle that reads binary contents from the file. <\/p>\n<p>Finally in step 3, we load the dictionary from the file to the config_dictionary variable via the <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html#pickle.load\" target=\"_blank\"><code>pickle.load<\/code><\/a> function.<\/p>\n<p>Once we had loaded the dictionary from the file to the <code>config_dictionary<\/code> variable, we use the <a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#print\" target=\"_blank\"><code>print<\/code><\/a> function to print the dictionary contents to the standard output.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-9r\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9r&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9r&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F585&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>There are times when it is more convenient for us to choose object serialization over database management systems for the persistency of the data that our Python scripts work with.  <\/p>\n<p>In this post, I document how we can save and load objects to and from file in Python using facilities from the pickle module.<\/p>\n","protected":false},"author":1,"featured_media":1244,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[25,368,369,226],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Python-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-9r","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/585"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=585"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/585\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1244"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=585"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=585"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=585"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}