简体   繁体   中英

How to write two consecutive lines from file in python?

old = open('./old.txt')
new = open('./new.txt','w')
for line in file:
    if '22%' in line:
        new.write(line)
new.close()

the above code writes lines containing 22% into a new file. what changes should be made to also write the line that comes immediately after the line containing 22%?

example: old.txt has

abc

def

g22%hi

jkl

mno

new.txt should have

g22%hi

jkl

You can use a flag or use next as others said in comments:

some_flag = False
for line in file:
    if some_flag:
        new.write(line)
        some_flag = False
    if '22%' in line:
        new.write(line)
        some_flag = True

new.close()

The simplest change you can do to your existing code, and solve the question is:

old = open('./old.txt')
new = open('./new.txt','w')
prevLine = ""
for line in file:
    if '22%' in line or '22%' in prevLine:
        prevLine = line
        new.write(line)
new.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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