簡體   English   中英

查找包含特定字符串的行並將其添加到新文件中

[英]looking for line containing specific string and added it into a new file

我想做的是在文本文件中查找字符串“ ESTABLISHED ”。 如果找到,它將把整行打印到另一個txt文件newestFile 問題是,它僅查找包含字符串“ ESTABLISHED ”的第一行,並將其保存到newestFile 我希望能夠復制並粘貼包含該字符串的每一行,而不僅僅是一行。

這是我的文字

Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)        rxbytes    txbytes
tcp4       0      0  192.168.1.6.50860      72.21.91.29.http       CLOSE_WAIT         892        691
tcp4       0      0  192.168.1.6.50858      www.v.dropbox.co.https ESTABLISHED      27671       7563
tcp4       0      0  192.168.1.6.50857      162.125.17.1.https     ESTABLISHED      17581       3642

和我的代碼:

def script(file, newestFile):
    with open(file, 'r') as r:
        for line in r:
            if "ESTABLISHED" in line:
               with open(newestFile, "w") as output:
                  output.writelines(line)
with open(newestFile, "w") as output:
    output.writelines(line)

在每個循環中,您都在重新創建newestFile 寫入模式( w )刪除文件並創建一個新文件(如果有的話)。 因此,每次找到ESTABLISHED ,您的代碼就會刪除舊代碼並創建新代碼。

不用w使用append( a )模式,如果沒有一個文件並且有文件,它將創建新文件,而是將您的值附加到文件中。

with open(newestFile, "a") as output:
    output.writelines(line)

您可能需要閱讀有關讀寫文件的更多文檔

暫無
暫無

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

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