在第二次读取期间在文本文件中查找项

2024-09-28 22:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序开始时,我用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文件


Tags: 文件of方法txtinputrawreturnif
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:57

调用f.readlines()后,您就到了文件的末尾。要返回到开始,以便可以再次查看,请调用f.seek(0)

def findFood(food):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in f.readlines():
        ...
    f.seek(0)

或者,您可以将文件内容导入列表:

def import_file(filename):
    with open(filename) as f:
        content = [line.strip() for line in f]
    return content

并使用它,而不是引用回该文件

def findFood(food, data):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in data:
        ...

那么你就不必担心回到起点了

相关问题 更多 >