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

Jos*_*eph 3 python writing file pickle

我正在尝试将多个变量保存到一个文件中。EG 在商店中保存一件商品,因此我尝试将商品的价格、名称和代码保存到一个文件中,并将多个商品保存到同一个文件中

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()
Run Code Online (Sandbox Code Playgroud)

Mik*_*rns 8

您绝对可以将多个对象保存到 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']
>>> 
Run Code Online (Sandbox Code Playgroud)

  • @brethvoice:是的。 (2认同)