When creating a process to save dictionary type data locally in Python
I was wondering, "What? How do you save it?"
Since I first learned about the existence of the pickle
module, I will leave it as a study note. (Finally saved in JSON)
--The pickle module allows you to save an object in a separate file in binary format. --However, the pickle module is not recommended for use from a security point of view. --Also, the saved file is Python-specific.
The pickle module allows you to save an object to a file in binary format.
The pickle module implements a binary protocol for serializing Python objects and restoring serialized objects. Python official documentation: pickle
By the way, "pickle" means "pickles". Does it come from saving objects that disappear quickly? What a cool
You can open the file in binary write mode and save the object you want to save with pickle.dump ()
.
createPickle.py
import pickle
d = {"name":"ndj", "age":25, "hobby": "YouTube"}
with open("sample.pickle", mode="wb") as f:
pickle.dump(d, f)
You can load it by opening the file in binary read mode and pickle.load
.
loadPickle.py
import pickle
d = {}
with open("sample.pickle", mode="rb") as f:
d = pickle.load(f)
By the way, objects other than dictionary type can be saved in the same way.
otherPickle.py
import pickle
def dumpPickle(fileName, obj):
with open(fileName, mode="wb") as f:
pickle.dump(obj, f)
dumpPickle("lst.pickle", [1,2,3,4,5])
dumpPickle("str.pickle", "helooooooo!!")
dumpPickle("int.pickle", 11114)
The same is true for reading.
otherPickle.py
import pickle
def loadPickle(fileName):
with open(fileName, mode="rb") as f:
return pickle.load(f)
lst = loadPickle("lst.pickle")
_str = loadPickle("str.pickle")
_int = loadPickle("int.pickle")
There is a warning at the top of the Pickle page in the official Python documentation.
Warning The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Python official documentation: pickle
I'm not so confident, but if the contents of the file are code in the process of converting the contents of the file to an object, it will be executed. .. It seems that you need to be careful about the usage because it will be a problem if unintended code is executed.
Recommended Posts