In use jupyter notebook Write python A lot of variables are generated in the process of code , And when it's closed or restart jupyter kernel Then all variables disappear , To see the variables, you have to run the code again , And want to be in another jupyter notebook It is even more troublesome to call variables in . Saving variables in long running code can save a lot of things .
Let's start !
The bag I use is pickle
1. You need to import the package before using it :
import pickle
2. After importing the package, you can start substantive operations , We define functions that hold and read variables .
Save variable functions :
def save_variable(v,filename):
f=open(filename,'wb')
pickle.dump(v,f)
f.close()
return filename
Read variable function :
def load_variavle(filename):
f=open(filename,'rb')
r=pickle.load(f)
f.close()
return r
3. Save variables and read variable operations .
Save variables : Put the variable results
Save in results.txt
In file .
filename = save_variable(results, 'results.txt')
Read variables : from results.txt
Read the variable content to results
.
results = load_variavle('results.txt')
Finally put the code together , Use which paragraph you want to use .
import pickle
def save_variable(v,filename):
f=open(filename,'wb')
pickle.dump(v,f)
f.close()
return filename
def load_variavle(filename):
f=open(filename,'rb')
r=pickle.load(f)
f.close()
return r
filename = save_variable(results,'results.txt')
results = load_variavle('results.txt')