[Python] You can save an object to a file by using the pickle module.

You can save the object using the pickle module

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)

wrap up

--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.

About the pickle module

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

Try using the pickle module

File creation

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)

File reading

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)

Objects other than dictionary type can also be saved

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")

It seems that you need to be careful when using it

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.

reference

Python Official: Pickle

Recommended Posts

[Python] You can save an object to a file by using the pickle module.
Save the object to a file with pickle
Save an array of numpy to a wav file using the wave module
[Python] If you create a file with the same name as the module to be imported, an Attribute Error will occur.
Python Note: When you want to know the attributes of an object
I tried using the Datetime module by Python
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
Convert the cURL API to a Python script (using IBM Cloud object storage)
Save the graph drawn by pyqtgraph to an image
Write data to KINTONE using the Python requests module
How to save a table scraped by python to csv
[Python] Save the video data imported by OpenCV as a serial number jpg file
Can you delete the file?
Save the pystan model and results in a pickle file
Why can I use the module by importing with python?
[python] Change the image file name to a serial number
How to switch the configuration file to be read by Python
Try to operate an Excel file using Python (Pandas / XlsxWriter) ①
Try to operate an Excel file using Python (Pandas / XlsxWriter) ②
How to import a file anywhere you like in Python
[Python] How to output a pandas table to an excel file
How to paste a CSV file into an Excel file using Pandas
Create a shell script to run the python file multiple times
Operate Maya from an external Python interpreter using the rpyc module
Settings for running a test each time you save a file in the editor using watchmedo (watchdog)
Extract the targz file using python
When you want to send an object with requests using flask
Try using the Python Cmd module
Check if you can connect to a TCP port in Python
Get the formula in an excel file as a string in Python
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
The story of making a tool to load an image with Python ⇒ save it as another name
[Python Kivy] How to get the file path by dragging and dropping
If you want a singleton in python, think of the module as a singleton
Have Alexa run Python to give you a sense of the future
A memo organized by renaming the file names in the folder with python
If you are told cannot by Python import, review the file name
[Python] How to read a csv file (read_csv method of pandas module)
Create a record with attachments in KINTONE using the Python requests module
I made a program to check the size of a file in Python
I tried to analyze the New Year's card by myself using python
How to sort by specifying a column in the Python Numpy array.
python3 How to install an external module
How to convert Python to an exe file
Create a graph using the Sympy module
Function to save images by date [python3]
Read the file line by line in Python
Read the file line by line in Python
An Introduction to Object-Oriented-Give an object a child.
From Django 1.8, you can pass a callable object to the choices attribute of forms.ChoiceField, which is very convenient.
[Python3] Code that can be used when you want to cut out an image in a specific size
<Python> A quiz to batch convert file names separated by a specific character string as part of the file name
If you want to make a Windows application (exe) that can be actually used now using only Python
How to save the feature point information of an image in a file and use it for matching
[Python3] Code that can be used when you want to change the extension of an image at once
[2015/11/19] How to register a service locally using the python SDK on naoqi os
Various ways to read the last line of a csv file in Python
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
If you want to make a TODO application (distributed) now using only Python
Save the setting conditions as a CSV file using UDF Manager in OCTA
I tried using the Python library "pykakasi" that can convert kanji to romaji.