I get stock price data with the following code:
for i in range(25200):
    time.sleep(1)
    with requests.Session() as s:
               data = {'ContractCode' : 'SAFMO98' }
               r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()
    for key, value in r.items():
        plt.clf()
        last_prices = (r[key]['LastTradedPrice'])   
        z.append(last_prices)
        plt.figure(1)
        plt.plot(z)
Sometimes my program gets disconnected or stops. Then I must re run the program and I loose all my data and program starts from the beginning. I am seeking a way to save data and reuse it after rerunning the program. How is it possible?
What should I add to my code for doing that?
EDIT: I edited my code like following, but neither of ways worked for me:
try:
    with open('3_tir.pickle', 'rb') as f:    
           last_prices = pickle.load(f)
           print("pickle loaded")
   #f = open("last_prices.txt", 'a+')
   #f.read()
except Exception:
    #f = open("last_prices.txt", 'a+')
    pass
for i in range(25200):
    time.sleep(1)
    with requests.Session() as s:
               data = {'ContractCode' : 'SAFMO98' }
               r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()
    for key, value in r.items():
        plt.clf()
        last_prices = (r[key]['LastTradedPrice'])   
        z.append(last_prices)
        plt.figure(1)
        plt.plot(z)
    with open('3_tir.pickle', 'wb') as f:
           pickle.dump(last_prices, f)
    #   f.write(last_prices)
    #   f.close()
 
     
    