![](/img/trans.png)
[英]python search for string in file return entire line + next line into new text file
[英]How to return next line in text file in python
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
我想要它,當它看到某個 header 像“食物”時它會在它下面打印一行。 我似乎無法讓它工作。 文本文件將像
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
只需使用索引。
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()
您可以嘗試以下方法:
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()
由於readlines()
返回文件中可以迭代的行列表,因此您可以簡單地通過其索引訪問后續行:
l = len(lines)-1
for i in range(l):
if 'Food' in lines[i]:
print(lines[i+1])
方法readlines()
返回列表 object,您可以將其轉換為迭代器,然后使用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()
如果文件非常大,一次讀取一行文件可能是有益的。 此代碼不會將完整文件加載到 memory 中,而是一次只加載一行:
def openFood():
with open("FoodList.txt") as f:
line = f.readline()
while line:
if 'Food' in line:
print(f.readline())
line = f.readline()
openFood()
結果:
Apple
注意:對於較小的文件,這種方法會比使用readlines()
方法將內容讀入 memory 慢很多。
readlines()
讀取文件中的所有行並返回一個列表。 您可以一次讀取和迭代一行(使用readline()
),或者讀取所有行並使用列表進行迭代(使用readlines()
)。
除了提到的方式之外,您還可以使用如下的bool
(我在這里使用了readlines()
):
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.