Render Python objects to a tempfile
Created | |
---|---|
Tags | notepython |
Python objects can be transformed and saved into files by using json and pickle packages.
For json :
import json
l2=[1,2,3,4,5]
# Render list into filetempt file
with open("json.tmp", 'w') as f:
json.dump(l2, f, indent=2)
# Read json filetempt file into list
with open("json.tmp", 'r') as f:
l3 = json.load(f)
print(l3)
For pickle :
import pickle
l2=[1,2,3,4,5]
# Render list into binary filetempt file
with open("pickle.tmp", 'wb') as f:
pickle.dump(l2, f, indent=2)
# Read binary filetempt file into list
with open("pickle.tmp", 'rb') as f:
l3 = pickle.load(f)
print(l3)
json file is readable but larger. pickle provides a compact binary file.