例如文件内容为:
this is the first line;
start
this is the second line;
this is the third line;
this is the forth line;
this is the fifth line;
end
this is the sixth line;
this is the seventh line;
“开始”和“结束”是标志,我想打印这两个标志之间的线条。我想要的结果是:
this is the second line;
this is the third line;
this is the forth line;
this is the fifth line;
那么,我该如何处理这个文件。
请您参考如下方法:
def read_sec(fle, start, end):
from itertools import dropwhile, takewhile
with open(fle) as f:
# drop lines until we reach start
dp = dropwhile(lambda x: not x.rstrip() == start,f)
next(dp) # skip start line
# take lines until we hit our end line
for line in takewhile(lambda x: x.rstrip() != end, dp):
yield line.rstrip()
print(list(read_sec("test.txt","start","end")))
输出:
['this is the second line;', 'this is the third line;', 'this is the forth line;', 'this is the fifth line;']
dropwhile 将一个条件作为第一个参数,将一个可迭代对象作为第二个参数,当您的条件为 True 时将丢弃元素,即我们还没有到达起始行,然后我们在dropwhile 对象跳过起始行并使用 takewhile ,它采用类似的 argumnets 在我们还没有到达结束行时继续取行,即我们还没有到达 "end"。
或者简单地在您点击起始行时使用嵌套循环并在您到达最后一行时返回:
def read_sec(fle, start, end):
with open(fle) as f:
for line in f:
if line.rstrip() == start:
for line in f:
if line.rstrip() == end:
return
yield line.rstrip()
print(list(read_sec("test.txt", "start", "end")))
输出:
['this is the second line;', 'this is the third line;', 'this is the forth line;', 'this is the fifth line;']
一个文件对象返回它自己的迭代器,所以当我们到达 start 行时,我们在文件对象上开始一个内部循环,它将从开始后的行开始,我们只是让出每一行直到我们到达end 我们刚刚返回以结束函数。
