Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to save multiple variables in python pickle?

Tags:

python

pickle

I am trying to save multiple variables to a file. E.G saving an item in a shop so I'm trying to save the items price,name and code to one file, and multiple items to the same file

def enter_item_info():
count = 0
count1 = 0
print("how many items are you entering?")
amount = int(input("Items = "))
data = [[0,1,2]] * amount




file = (open('fruit.txt','wb'))
while count < amount:




    data[0 + count1][0] = input("Code")


    data[0 + count1][1] = input("NAme")

    data[0 + count1][2] = input("Price")
    count1 = count1 + 1
    count = count + 1


    print("")



pickle.dump(data , file)
file.close()
amount = str(amount)
file1 = (open('amount.txt','wb'))
pickle.dump(amount , file1)
file1.close()
like image 849
Joseph Avatar asked Dec 25 '22 10:12

Joseph


1 Answers

You definitely can save multiple objects to a pickle file, either by putting the objects in a collection (like a list or dict) and then pickling the collection, or by using multiple entries in a pickle file… or both.

>>> import pickle
>>> fruits = dict(banana=0, pear=2, apple=6)
>>> snakes = ['cobra', 'viper', 'rattler']
>>> with open('stuff.pkl', 'wb') as f:
...   pickle.dump(fruits, f)
...   pickle.dump(snakes, f)
... 
>>> with open('stuff.pkl', 'rb') as f:
...   food = pickle.load(f)
...   pets = pickle.load(f)
... 
>>> food
{'pear': 2, 'apple': 6, 'banana': 0}
>>> pets
['cobra', 'viper', 'rattler']
>>> 
like image 73
Mike McKerns Avatar answered Mar 31 '23 22:03

Mike McKerns