itemsInExistence = []
item = {}
item['name'] = input("What do you want the new item to be called? ")
item['stats'] = int(input("What is its stat? "))
item['rank'] = int(input("What is its base rank? "))
item['amount'] = int(input("How many of it are there? "))
for i in range(item['amount']):
itemsInExistence.append(item)
def save_list2():
with open('itemsleft.txt', 'wb') as f:
i = 0
for item in itemsInExistence:
pickle.dump(itemsInExistence, f)
i += 1
我试图正常保存它和泡菜,但是都没有保留字典的值。我需要将字典保存到文件中,并从文件中检索“ stats”,“ rank”,“ amount”仍然是整数,并且与该行的其余部分分开。 (请记住,itemsInExistence中将有多个保存的项目,要保存和加载。)
def save_list2():
ii = 0
for i in itemsInExistence:
d = itemsInExistence[ii]
json.dump(d, open(files2, 'w'))
ii += 1
def load_list2():
with open(files2,'r') as a:
for line in a:
line = line.strip()
itemsInExistence.append(line)
您可以使用JSON
格式将字典存储到文件中,这很容易
import json
file = "foofile"
d = dict()
# fill d
# save data : format the dict to a string and it into the file
json.dump(d, open(file, 'w'))
# read data : read the file's content and parse to a dict
a = json.load(open(file))