【问题标题】:Is there a way to save multiple variables in python pickle?有没有办法在 python pickle 中保存多个变量?
【发布时间】:2016-01-08 09:55:48
【问题描述】:

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

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

【问题讨论】:

  • 你尝试了什么,遇到了什么问题?
  • 您的代码没有正确缩进 - 请确保所有缩进都是应有的,因为这在 Python 中相当重要。

标签: python file pickle writing


【解决方案1】:

您绝对可以将多个对象保存到一个 pickle 文件中,方法是将对象放入一个集合(如列表或 dict)然后对集合进行 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']
>>> 

【讨论】:

  • 那么 load 会按照丢弃的顺序依次抓取一个项目?
  • @brethvoice:是的。
【解决方案2】:

来自the documentation(强调==&gt;):

可以腌制以下几种:

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

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

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多