我正在读取一个大的文本文件,我需要从一个特定的行读取一个数字。该文件如下所示:
....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....
我想从“签名”行(即ABCD
)后面的2行中读取数字,这是唯一的。现在我要做的是:
with open(filename,'r') as f:
for line in f:
if line.rstrip('\n') == 'ABCD':
continue
但是continue
只将for循环推进了1次迭代。那么,我如何才能再进行一次迭代以得到我实际需要的行呢?
发布于 2016-07-19 09:19:55
如果您想坚持这种方法,那么就这样做:
f = open(filename,'r'):
while f.readline().rstrip('\n') != 'ABCD': # this will advanced the pointer to the ABCD line
continue
f.next() # to skip over the unnecessary stuff
desiredNumber = f.readline() # desired line
我认为regex看起来要好得多,但是如果您想要完成工作,就在这里。
发布于 2016-07-19 09:14:57
如果您根本不需要从跳过的行中获得任何信息,则可以在continue
ing之前通过一行手动推进文件:
with open(filename,'r') as f:
for line in f:
if line.rstrip('\n') == 'ABCD':
next(f) # The next iteration of the for loop will skip a line
continue
如果您需要该文件中的唯一内容是这一行,那么根本不需要continue
。只需跳过一行,抓住下一行,做您需要做的任何事情,然后break
从for
循环中退出,所有这些都来自于if
块。
发布于 2016-07-19 11:36:23
我更喜欢@Jim对next()
的使用,但另一个选择是只使用一个标志:
with open(filename,'r') as f:
skip_line = False
for line in f:
if line.rstrip('\n') == 'ABCD':
skip_line = True
continue
if skip_line == True:
skip_line = False
else:
print(line)
https://stackoverflow.com/questions/38464529
复制相似问题