我有一个文件,我想一次得到每一行,但一旦它到了一个特定的行,我需要得到下几行的信息。
下面是代码示例:
rofile = open('foo.txt', 'r')
for line in rofile:
print line
if(line.strip() == 'foo'):
line = line.next()
print line
line = line.next()
print line
line = line.next()
print line
当我第二次返回并循环时,第一个print语句应该打印文件中的第5行。有什么可能的办法吗?
编辑:很抱歉没有澄清细节。rofile
是我正在遍历的文件对象。使用文件时,next()
是否是获取下一行的真正方法,我不知道。我对python中的文件操作没有太多经验。
根据
rofile
对象的类型,我可以想出两种方法来实现这一点。字符串列表
如果您可以让它只是组成文件行的字符串列表:
Iterable
如果文件已经是iterable:
你可以在我写的这个快速示例中看到,它将以这种方式作为iterable工作:
可以使用
iter
将对象转换为支持next
的iterable。正如注释中指出的,如果您的对象已经是迭代器,那么您不需要担心
iter
(这是file
对象的情况)。但是,我把它留在这里,因为它适用于任意iterable(例如list
)的情况。如果您实际上不想对每一行都执行操作,请不要使用
for
循环。一种选择可能是:相关问题 更多 >
编程相关推荐