【发布时间】:2020-04-25 20:04:30
【问题描述】:
所以,虽然我只是涉足编码和试验,但我想为我的 D&D 活动需要的 170 个(目前)NPC 创建一个易于交互的数据库。
事实证明,在不理解代码的情况下将代码块混在一起并不总是有效,令人震惊。
所以,这是我的代码,虽然我确信它会让你流血,但我只需要让它工作:
#import pickle
import pickle
#NPC ID generator
counter=1
NPCS=[]
while counter<=170 :
NPCS.append(counter)
counter+=1
if len(NPCS)==170:
print ("True")
else :
print ("False") ; raise SystemExit
#Attributes
name=[] ; occupation=[];weakness=[];need=[];desire=[];enemy=[];rumor=[];secret=[];passion=[]
redeemdamningquality=[];happy=[];occdesire=[];occcomplication=[];pcopinion=[];accomplish=[]
magical=[];politinfl=[];resource=[];intel=[];research=[]
NPCatt=[name,occupation,weakness,need,desire,enemy,rumor,secret,passion,redeemdamningquality,happy,occdesire,occcomplication,pcopinion, accomplish,magical,politinfl,resource,intel,research]
#open a pickle file
newfile = 'NPCatt.pk'
#load your data back to memory when you need it
with open(newfile, 'rb') as fi:
NPCatt = pickle.load(fi)
# Data Input
print ("Enter the numerical code of the NPC you wish to modify")
raw=int(input())
if raw != ValueError :
print ("Enter Name of NPC" + str(raw) ) ; a=input()
if a!="":
name.insert(raw+1,a);print ("Name Inserted Successfully")
else:
print ("Skipped!")
print ("Enter Occupation of NPC" + str(raw) ) ;a=input()
if a!="":
occupation.insert(raw+1,a);print("Occupation Inserted Successfully")
else:
print ("Skipped!")
else :
print ("BAD VALUE")
for x in (NPCatt) :
if len(x)!=0 :
print (x)
elif len(x)>=170:
print (x) ; print ("Has too many items")
else :
print (str(x) + "is empty")
with open(newfile, 'wb') as fi:
# dump your data into the file
pickle.dump(NPCatt, fi)
我不确定的是为什么我输入的数据在代码运行之间没有“保存”。 请帮忙
【问题讨论】:
-
你能否为你的问题做一个最小可重现的例子。目前,如果我尝试加载一个腌制对象,对其进行修改,然后将其再次腌制回文件,这些更改确实会被保存。
-
老实说克里斯,我不知道该怎么做。我可以告诉你,代码运行没有错误或异常,只是没有保存我想要的数据。
-
我没有,怎么可能?
-
不是文件系统问题。这是 OP 如何理解变量工作的问题。
-
@Icarus 我查看了您的代码并发现了问题并发布了一个答案,解释了它发生的原因以及如何更改它以在您当前的代码中工作,但也建议您可能有猜测这段代码不是最好的方法