有没有办法在python pickle中保存多个变量?

时间:2016-01-08 09:55:48

标签: python file pickle writing

我正在尝试将多个变量保存到文件中。 E.G在商店中保存商品,以便我尝试将商品价格,名称和代码保存到一个文件,将多个商品保存到同一个文件

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

2 个答案:

答案 0 :(得分:3)

您肯定可以将多个对象保存到pickle文件中,方法是将对象放在集合中(如列表或字典),然后对该集合进行pickle,或者在pickle文件中使用多个条目......或者两者兼而有之。

>>> 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']
>>> 

答案 1 :(得分:0)

来自the documentation(强调==>):

  

可以腌制以下类型:

None, True, and False
integers, long integers, floating point numbers, complex numbers
normal and Unicode strings
===> tuples, lists, sets, and dictionaries containing only picklable objects
functions defined at the top level of a module
built-in functions defined at the top level of a module
classes that are defined at the top level of a module
instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section The pickle protocol for details).

因此,您可以将所有数据存储在列表和/或词典中,您应该没问题。