Reputation: 19
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
Upvotes: 2
Views: 417
Reputation: 325
readlines()
reads all the lines in a file and returns a list. You could either read and iterate one line at a time (using readline()
), or read all the lines and use the list for iteration (using readlines()
).
Apart from the ways mentioned, you could also use a bool
like below (I've used readlines()
here):
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
trigger = "Food"
triggerfound = False
for line in lines:
if triggerfound:
print(line)
triggerfound = False
if trigger in line:
triggerfound = True
openFood()
Upvotes: 0
Reputation: 3030
Reading a file one line at a time can be beneficial if the file is very large. This code will not load the full file into memory, but only one line at a time:
def openFood():
with open("FoodList.txt") as f:
line = f.readline()
while line:
if 'Food' in line:
print(f.readline())
line = f.readline()
openFood()
Result:
Apple
Note: This method will be a lot slower for smaller files, than reading the contents into memory using the readlines()
method.
Upvotes: 0
Reputation: 11346
Method readlines()
returns list object, you can convert it to an iterator and then use next
function:
def openFood():
with open("FoodList.txt") as f:
lines = iter(f.readlines())
for line in lines:
if 'Food' in line:
print(next(lines))
openFood()
Upvotes: 0
Reputation: 1217
Since readlines()
returns a list of the lines in the file that you can iterate over, you can simply access the subsequent line via its index:
l = len(lines)-1
for i in range(l):
if 'Food' in lines[i]:
print(lines[i+1])
Upvotes: 0
Reputation: 8521
Can you try the following:
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for ind, line in enumerate(lines):
if 'Food' in line:
try:
print(lines[ind + 1])
except:
print('No line after "Food"')
openFood()
Upvotes: 0
Reputation: 640
Just use the index.
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
Upvotes: 2