简体   繁体   English

如何在Python中访问文件(.txt)中的下一行

[英]How to access next line in a file(.txt) in Python

I have a file and I open it and then I check for few things. 我有一个文件,我打开了它,然后检查了几件事。 If the line starts with "E PARAM" and also has "OOPS1" in it somewhere then I want to check that the next line starts with " E PARAM". 如果该行以“ E PARAM”开头,并且在某处也有“ OOPS1”,那么我要检查下一行是否以“ E PARAM”开头。 If not I will make a new file and copy it there till the time I dont hit another "E PARAM" line. 如果没有,我将制作一个新文件并将其复制到那里,直到我没有击中另一条“ E PARAM”行。 Since Python doesnt have a next() option... what can help me here 由于Python没有next()选项...在这里可以帮到我什么

import string
import os


A = "k_trap_cur"
B = open(A, 'r+')
lines = B.readline()

for lines in B:
    if lines.startswith("E PRAM"):
        if "OOPS: 1" in lines:
            while lines.next().startswith("E PARAM") == False: // HERE I want to access next line
                print " YES"

If I understood you right: 如果我没看错:

b = open(a, 'r+')
for line in b:
    if line.startswith("E PRAM") and "OOPS: 1" in line:
        next_line = next(b)
        # do whatever you need

Files provide what is called an “Iterator protocol” and that's why they work in for -loops. 文件提供了所谓的“迭代器协议”,这就是它们在for -loops中工作的原因。 You can also call next function on them manually, if you want. 如果需要,还可以手动调用它们的next函数。 Check PEP-234 for more details. 有关更多详细信息,请检查PEP-234

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

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