简体   繁体   English

Python:对于包含文件的循环,如何获取forloop中的下一行?

[英]Python: For loop with files, how to grab the next line within forloop?

I have a file that I want to get each line at a time, but once it gets to a specific line, I need to get the next few lines information. 我有一个文件,我想一次获得每一行,但一旦它到达一个特定的行,我需要获得接下来的几行信息。

Here is a code sample: 这是一个代码示例:

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

When I come back around and loop for the second time, that first print statement should print the 5th line in the file. 当我第二次回来并循环时,第一个print语句应该打印文件中的第5行。 Is there any possible way to do this? 有没有办法做到这一点?

EDIT: Sorry for not clarifying the details. 编辑:很抱歉没有澄清细节。 rofile is a file object that I'm iterating through. rofile是我正在迭代的文件对象。 Whether next() is the real method to obtain the next line when using a file, I don't know. next()是否是使用文件时获取下一行的真正方法,我不知道。 I don't have much experience with file manipulation in python. 我对python中的文件操作没有多少经验。

You can use iter to convert your object into an iterable which supports next . 您可以使用iter将对象转换为支持next的iterable。

irofile = iter(rofile)
for line in irofile:
    print line
    if(line == 'foo'):
        line = next(irofile)  #BEWARE, This could raise StopIteration!
        print line

As pointed out in the comments, if your object is already an iterator, then you don't need to worry about iter (this is the case with file objects). 正如在评论中指出,如果你的对象已经是一个迭代器,那么你就不需要担心iter (这是与本案file对象)。 However, I leave it here as it works for the case of any arbitrary iterable (eg list s). 但是,我把它留在这里,因为它适用于任何可任意迭代的情况(例如list s)。

Depending on the type of object that rofile is, I can think of a couple of ways to do this. 根据rofile的对象类型,我可以想到几种方法来做到这一点。

List of strings 字符串列表

If you can get it to be simply a list of strings that make up the lines of the file: 如果你可以把它简单化为构成文件行的字符串列表:

for index, line in enumerate(rofile):
   if line == 'foo':
       for a in range(index, index + HOW_MANY_LINES_YOU_WANT):
           print rofile[a]

Iterable 可迭代

If the file is already an iterable: 如果文件已经是可迭代的:

for line in rofile:
    print line
    if line == 'foo':
        for a in range(3): # Just do it 3 times
            print line.next()
            # After this happens and the for loop is restarted,
            # it will print the line AFTER

You can see in this quickie example I wrote that it'll work this way as an iterable: 您可以在这个快速示例中看到我写道它将以可迭代的方式工作:

>>> k = iter([1,2,3,4])
>>> for a in k:
    print 'start loop'
    print a
    if a == 2:
        print 'in if'
        print k.next()
        print 'end if'
    print 'end loop'


start loop
1
end loop
start loop
2
in if
3
end if
end loop
start loop
4
end loop

Don't use a for loop if you don't actually want to do something for every line. 如果您实际上不想每一行做某事,请不要使用for循环。 One option might be: 一种选择可能是:

try:
    while True:
        line = file.next()
        #do stuff
        if line == 'foo':
            #do other stuff
except(StopIteration):
     #go on with your life

Here's a simple way to do it for a file object: 这是为文件对象执行此操作的简单方法:

with open('foo.txt', 'r') as rofile:
    for line in rofile:
        print line,
        if line.strip() == 'foo':
            for _ in xrange(3):  # get the next 3 lines
                try:
                    line = rofile.next()
                except StopIteration:
                    break
                print line,

The try/except is needed in case there aren't 3 more lines after a 'foo' line is seen. 如果在看到'foo'行之后没有3行,则需要try / except。

我有一个类似的问题,并使用continue语句代替我的情况

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从列表 python 中获取下一个整数 - how to grab next-in-line integers from list python 如何在 Forloop 中的 Python 中将 Append 字符串转换为字典 - How To Append String To Dictionary in Python within Forloop Python:如果在一行中遇到字符,如何转到下一行 - Python: how to go to the next line if you encounter a character within a line 如何在不更改迭代的情况下获取for循环中文件中的下一行 - How to get next line in a file within a for loop without changing iteration 如何在python的循环中移至循环的下一个迭代? - How to move onto the next iteration of a loop within a loop in python? 如何在Python中使用迭代器从文件中获取下一行,检查其是否与正则表达式匹配,并在匹配时添加到数组中? - How to use an iterator in Python to grab next line from file, check if it matches regex, and add to an array if it matches? 如何在for循环中读取下一行? 蟒蛇 - How I can read the next line in a for loop? Python 如何在python中的匹配行之后抓取行 - How to grab the lines AFTER a matched line in python 如何使用fileinput中的“for line”在嵌套循环中迭代到文件的下一行? - How would I iterate onto the next line of a file within a nested loop using “for line” in fileinput? 如何读取目录中的文件,然后出来读取下一个目录 python 中的文件? - How do I read files within directory and then come out and read files within next directory python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM