我正在尝试将配方的成分写入阵列中进行酸洗,然后重新打开以供进一步使用。该程序需要能够采取任何数量的成分,因此通过成分的数量循环三个输入。
recipedetails=[] #starts array
for i in range (ing_number): #Loops 3 intented code by in_number amount of times
ing_name = input ("Enter ingredient name: ") #Ingredient name variable
ing_amount = int (input ("Enter quantity of ingredient ")) #Quantity variable
ing_unit = input ("Enter unit of ingredient: ") #Unit variable
recipedetails.append ((ing_name, ing_amount, ing_unit)) #closes array
recipe = open(rec_name+".dat", "wb") #Creates .dat file with recipe name as file name.
pickle.dump(recipedetails, recipe) #Adds this info to .dat file
然而,当我输入例如4个成分时,数组只将3保存到.dat文件中。我不明白为什么会这样,因为它没有覆盖最后一个成分,它似乎只是忽略了它。如何将所有循环变量添加到数组和.dat文件中?
print ("Create Recipe") #Shows user has opted to create recipe
rec_name = input ("Enter recipe name: ") #Prompts user for recipe name.
ing_number = int (input ("Enter number of ingredients: ")) #Prompts user for number of ingredients
people = str (input ("Enter number of people: ")) #Prompts user for number of people
f = open(rec_name+"people.txt", 'w')
f.write(people)
f.close()
recipedetails=[] #starts array
for i in range (ing_number): #Loops 3 intented code by in_number amount of times
ing_name = input ("Enter ingredient name: ") #Ingredient name variable
ing_amount = int (input ("Enter quantity of ingredient ")) #Quantity variable
ing_unit = input ("Enter unit of ingredient: ") #Unit variable
recipedetails.append ((ing_name, ing_amount, ing_unit)) #closes array
recipe = open(rec_name+".dat", "wb") #Creates .dat file with recipe name as file name.
pickle.dump(recipedetails, recipe) #Adds this info to .dat file
print (recipedetails)#Prints ingredients that user has added.
添加完整代码