Write non-string datatypes to files…
We all know about the write() function used to write a string to a file. But how do we write non-string datatypes like dictionaries, hashes to a file using python ?
Python has a module named pickle, which would convert the python object hierarchy into a byte stream (the vice-versa can also be achieved). The data type used by pickle is python-specific.
In my case, I had to write a hash to a file. Here is what I did…
with open(“my_file.txt”, “w”) as my_file:
pickle.dump(my_hash, my_file)
my_file.close()
here, pickle.dump() would dump/write my hash/dictionary into the file I wanted.
We know read() function is to read the contents from a file, but it reads only the string contents. It is not going to help here.
We have pickle.load() function to read the object from the open file. Here is what I did…
with open(“my_file.txt”, “r”) as my_file:
my_hash = pickle.load(my_file)
my_file.close()
Now, my_hash has the hash content read from the file. Do not forget to import pickle.
Where there is a will, there is a way 🙂