当循环当前行时,如何处理下一行?

2024-03-29 06:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试将vba宏转换为python。python中的第一步,所以不要扔石头,如果这么明显的话

Reading a text file 
processing each line
if the line contains a keyword 
    I want to process the next 2 lines 
    (which have the data I need to extract)

如何选择线路I+1&;如果当前(有效)行为i,则为i+2

谢谢


2条回答

这是在python中实现这一点的一种方法:

with open ('text.txt') as text_file :
    for line in text_file :
        if 'keyword' in line :
            first_line = text_file.readline ()
            second_line = text_file.readline ()

print (first_line, second_line)

以下是一些让您开始学习的代码:

with open('path/to/file') as f:
    for line in f:
        if 'keyword' in line:
            line = f.readline() # line i+1 
            line = f.readline() # line i+2 

别忘了用实际值替换path/to/filekeyword(并保持周围的''

相关问题 更多 >