{"id":11121,"date":"2023-01-05T16:44:15","date_gmt":"2023-01-05T11:14:15","guid":{"rendered":"https:\/\/pynative.com\/?p=11121"},"modified":"2023-01-05T16:50:55","modified_gmt":"2023-01-05T11:20:55","slug":"python-save-dictionary-to-file","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-save-dictionary-to-file\/","title":{"rendered":"Python Save Dictionary To File"},"content":{"rendered":"\n
In this lesson, you\u2019ll learn how to save a dictionary<\/a> to a file in Python. Also, we’ll see how to read the same dictionary from a file.<\/p>\n\n\n\n In this lesson, you\u2019ll learn how to<\/strong>:<\/p>\n\n\n\n Dictionaries<\/a> are ordered collections of unique values stored in (Key-Value) pairs. The below steps show how to use the pickle module to save the dictionary to a file. <\/p> The pickle module<\/a> is used for serializing and de-serializing a Python object structure<\/strong>. Whenever we write content into a file, we have to open the file in one of the specified access modes. Open a file<\/a> using the built-in function called Now, we’ll use the Use a pickle module’s Let’s see the below example of how you can use the \n
dump()<\/code> method of a json module to write a dictionary in a json file.<\/li>\n\n\n\n
Table of contents<\/h2>
How to save a dictionary to file in Python<\/h2>\n\n\n\n
Pickling\u201d is the process whereby a Python object is converted into a byte stream, and \u201cunpickling\u201d is the inverse operation whereby a byte stream (from a binary file) is converted back into an original object.
We can save a dictionary object as a serialized byte sequence into a file using the pickle module. Also, we can read them from a file into a Python script by unpickling them.<\/p> <\/li>open()<\/code>. This function takes two parameters, filename and access mode, and returns the file pointer.
To open a binary file for writing, use the wb<\/strong><\/code> access mode. After you open the file for writing<\/a>, the FileHandle is placed at the beginning of the file, and existing content will be truncated. A new file is created if the file doesn’t exist.<\/p> <\/li>
dump()<\/strong><\/code> method to save the dictionary into a file.
The dump()<\/code> method writes the pickled representation of the Python object to the open file. In our case, The dictionary object gets converted into a byte stream.<\/p> <\/li>
load()<\/strong><\/code> method to read the same dictionary from a file.<\/p> <\/li><\/ol><\/div>\n\n\n\n
Example: save a dictionary to file<\/h3>\n\n\n\n
pickle<\/code> module to save a dictionary to a
person_data.pkl<\/code> file.<\/p>\n\n\n