在我的程序开始时,我用f = open("foods.txt", "r+")
打开了一个文件。后来我调用了我创建的这个方法
def findFood(food):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in f.readlines():
print line
duplicateFound = re.search(foodRegex, line)
if duplicateFound.group('food') == food:
return duplicateFound
else:
return False
但是,我再次运行该方法。但是我的程序没有按我希望的方式运行。具体地
def build_meal_plan():
number_of_items = int(raw_input("How many items would you like to add to your meal plan? "))
count = 0
while number_of_items > 0:
print count
food = raw_input("Enter in food name: ")
print food
if findFood(food):
servings = int(raw_input("Number of servings: "))
else:
print "Food not found! Try again? (y/n): ",
choice = raw_input()
if choice == 'y' or choice == "yes":
number_of_items += 1
else:
return
但是,在我的findFood
方法的第二次运行期间,我无法找到我知道存在于.txt
文件中的项。我不知道为什么我找不到第一次运行时在文本文件中找到的相同项目。我的假设是,您只能浏览一次txt文件
调用
f.readlines()
后,您就到了文件的末尾。要返回到开始,以便可以再次查看,请调用f.seek(0)
:或者,您可以将文件内容导入列表:
并使用它,而不是引用回该文件
那么你就不必担心回到起点了
相关问题 更多 >
编程相关推荐