假设TXT文件中的所有部分都以“-”开头,您可以创建两个字符串标志,并将它们用作嵌套for循环中的检查,如下所示:
import os
import sys
def get_ingredients_from_file():
recipe_file = open("/Filepath/", "r")
final_ingredients_list = list()
string_flag1 = "-Ingredients"
string_flag2 = "-"
for line in recipe_file:
if line.startswith(string_flag1): #Line is ingredients
for line in recipe_file:
if not line.startswith(string_flag2): #Loop until second string flag is encountered
final_ingredients_list.append(line) #append lines to the list
else:
break
希望这有帮助。