Thanks for the comments, yes I am aware of using JSON and pickle, but I was more interested having a .txt file. I worked around my problem and found the solution as below:
First I define a MyEncoder class as:
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(MyEncoder, self).default(obj)
As my keys are strings and my values are arrays, before writing the key-value pairs I dump the values as
dict_imageData [key] = json.dumps(np.float32(np.array(values)), cls = MyEncoder)
Now, I write the dictionary to the file as
with open('dict_imageData.txt', 'a') as file:
file.write(json.dumps(dict_imageData))
file.write("\n")
For reading back the dictionary from the .txt file one I use eval
with open('dict_imageData.txt','r') as inf:
lineno = 0
for line in inf:
lineno = lineno + 1
print("line number in the file: ", lineno)
dicts_from_file = dict()
dicts_from_file = (eval(line))
for key,value in dicts_from_file.items():
print("key: ", key, "value: ", value)