0

I am trying to save a list of objects and its corresponding attributes that go along with it. In the following example you can see that I first, define the list of objects and attributes, and then save it. Once the file has been saved, I delete the list to show that it is empty, but when I call the loading function, my list remains blank. Does anyone know why ?

import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

class Define_Companies():

    company_list = []

    def run_this(self):

        for x,y in enumerate(range(0,6)):
            company_list_object = Company(x,y)
            Define_Companies().company_list.append(company_list_object)


        for x in Define_Companies().company_list:
            print(x.name)

Define_Companies().run_this()

def save_this_information():

    with open('company_data.pkl', 'wb') as output:
        pickle.dump(Define_Companies().company_list, output, pickle.HIGHEST_PROTOCOL)

Define_Companies().company_list.clear()
save_this_information()

def load_the_information():

    with open('company_data.pkl', 'rb') as input:
        Define_Companies().company_list = pickle.load(input)
    print(Define_Companies().company_list)

load_the_information()

Output:

0
1
2
3
4
5
[]
S.McWhorter
  • 151
  • 1
  • 1
  • 15

1 Answers1

0

You call Define_Companies().company_list.clear() right before your save function, which clears all elements in the list. You are trying to save an empty list.


Also note that you don't need to have an instance of Define_Companies to access the class variable company_list because it is bound to the class, not an instance. to access the list you can just type Define_Companies.company_list.

sam-pyt
  • 1,027
  • 15
  • 26