我有一个文本文件,其中包含文本块,每个文本块由换行符分隔。有M
块,每个块都有N
行文本。我现在想阅读m
块中每个块的n
行,其中n<=N
和m<=M
.
我尝试了类似于以下内容的方法:
num_blocks = 4 # or whatever value I choose
num_lines = 3 # or whatever value I choose
with open('file.txt', 'r') as f:
lines = f.readlines()
block_num = 0
line_num = 0
for line in lines:
# do something with the line .....
line_num += 1
# has the specified number of lines been read?
if line_num == num_lines:
block_num += 1
# has the specified number of blocks been read?
if block_num == num_blocks:
break;
else:
line_num = 0
但是,当n<N
时,我需要跳过当前块中的剩余行。我试过把
if line != 'n':
continue
# do something with the line .....
,但这会跳过整个第一个块。
或者,我尝试创建一个迭代器it = lines.iter()
并相应地递增每个迭代器。这种方法的问题在于无法知道何时到达文件末尾。readlines()
为我执行此操作,但是如果我使用的是交互器,我不知道如何知道何时到达最后一行。
有什么帮助吗?谢谢!
您可以像这样测试迭代器的结尾:
try:
it.next()
except StopIteration:
*do something*
停止迭代异常是迭代器在没有剩余迭代内容时抛出的异常。