首先,我要道歉,因为我是Python的初学者。无论如何,我有一个Python程序,可以在其中创建具有一般形式的文本文件:
Recipe Name:
Item
Weight
Number of people recipe serves
而我想做的就是让程序能够检索配方并为不同数量的人重新计算成分。程序应输出配方名称,新人数和针对新人数的修订数量。我能够检索配方并输出配方,但是我不确定如何为不同数量的人重新调配配料。这是我的代码的一部分:
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
最佳答案
我必须编辑几次,因为我使用的是Python 2.7.5,但这应该可以工作:
import time
def modify_recipe():
Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
with open(Choice_Exist + ".txt", "r+") as f:
content = f.readlines()
data_list = [word.replace("\n","") for word in content]
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like: "))
print data_list[0]
print data_list[1]
print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
print ServRequire
modify_recipe()
关于python - 编写和编辑文件(Python),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29130328/