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

标签 python pickle

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

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

最佳答案

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

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

关于python - 有没有办法在 python pickle 中保存多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34674094/

相关文章:

python - 在 python 中使用 pickle 和 for 循环从文件中读取

Python pickle 槽错误

python-2.7 - 使用 dill 加载 pkl 文件

python - Python 中的十进制到二进制半精度 IEEE 754

python 继承。为什么这么乱?

python - 如何删除所有已定义的 SymPy 符号而不明确列出它们?

python - 为什么 Pandas 在读取 pickle 文件时会尝试导入模块?

python - json.dumps() 适用于 python 2.7 但不适用于 python 3

python - 通过起始字符选择元组中的元素

python - 在 2048 中创建一个 shift 函数