簡體   English   中英

搜索字符串,並使用Python將其及其下一行寫到新的文本文件中

[英]Search a string and write it in a new text file along with its next line by using Python

我正在用Python編寫代碼,以在巨大的文本文件中搜索字符串,該字符串每10-15行出現一次,並將其下一行復制到另一個文本文件中。 我是Python的初學者,所以不確定什么是最好的方法。 我正在嘗試使用以下腳本:

name = raw_input('Enter file:')
    with open(name) as f:
        with open("output.txt", "w") as f1:
            for line in f:
                if "IDENTIFIER" in line:
                    f1.write(line)

之后,在輸出文件中需要的是找到此字符串后的下一整行。

我想像line + 1這樣的東西在Python中不可用。

在輸入文本IDENTIFIER之后,如何跳到下一行並將其寫到輸出文件中?

with open("file_in.txt") as f:
   with open("file_out.txt","w") as f2:
        for line in f:
            if "my_test" in line:
                f2.write(line.rstrip("\n")+next(f)) # the next line :P

您可以使用flag變量:

flag = False

name = raw_input('Enter file:')
with open(name) as f:
    with open("output.txt", "w") as f1:
        for line in f:
            if flag:
                f1.write(line + '\n')
                flag = False  
            if "IDENTIFIER" in line:
                f1.write(line)
                flag = True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM