简体   繁体   English

如何使用fileinput中的“for line”在嵌套循环中迭代到文件的下一行?

[英]How would I iterate onto the next line of a file within a nested loop using “for line” in fileinput?

I have eliminated some of the nested loops for simplicity of the example. 为了简化示例,我已经删除了一些嵌套循环。

I am iterating over a file line-by-line using fileinput . 我正在使用fileinput遍历文件。 If the line meets a certain condition I want it to replace all future lines with '' until it meets the condition again. 如果线路满足某个条件,我希望它用''替换所有未来的线路,直到它再次满足条件。

import re
import fileinput
with fileinput.FileInput("survey.qsf", inplace=True, backup='.bak') as file:
    for line in file:
        if re.match(r'l'+datamap[i][2]+'.*$',line)!=None:
            line=re.sub(r'.*$','',line)
            while re.match(r'lQID\d*$',line)==None:
                line=re.sub(r'.*$','',line)
                next(line)

I used "next(line)" as a placeholder as I can't figure out how to iterate to the next line without breaking out of the inner loop. 我使用“next(line)”作为占位符,因为我无法弄清楚如何在不突破内循环的情况下迭代到下一行。

I want to be able to iterate through the lines to have: 我希望能够遍历这些行:

lQID44
xyz
xyz
lQID45

output as: 输出为:

[blank line]
[blank line]
[blank line]
lQID45

Thanks. 谢谢。

next takes the iterator as its argument. next迭代器作为参数。

while re.match(r'lQID\d*$',line)==None:
    line=re.sub(r'.*$','',line)
    try:
        line = next(file)  # Not next(line)
    except StopIteration:
        break

As an aside, there's no need to use re.sub to replace the entire line with an empty string; re.sub ,没有必要使用re.sub用空字符串替换整行; line = '' would suffice. line = ''就足够了。

(Also, assigning to line doesn't make changes to the actual file; inplace=True just means that you can write to file as well as read from it, but you have to explicitly write to the file, using print or file.write .) (另外,分配给line不会对实际文件进行更改; inplace=True只表示您可以写入 file以及从中读取file ,但您必须使用printfile.write显式写入文件。 。)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM