简体   繁体   English

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

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

What I'm trying to do is look for the string " ESTABLISHED " within my text file. 我想做的是在文本文件中查找字符串“ ESTABLISHED ”。 If it is found, it will print the entire line onto another txt file newestFile . 如果找到,它将把整行打印到另一个txt文件newestFile Problem is, it only looks for the first line that contains the string " ESTABLISHED ", and saves it onto newestFile . 问题是,它仅查找包含字符串“ ESTABLISHED ”的第一行,并将其保存到newestFile I want to be able to copy and paste each line containing that string, not just one. 我希望能够复制并粘贴包含该字符串的每一行,而不仅仅是一行。

Here is my text 这是我的文字

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

and my code: 和我的代码:

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)

In each loop you are re-creating newestFile . 在每个循环中,您都在重新创建newestFile Write mode ( w ) deletes the file and creates new one if there is one. 写入模式( w )删除文件并创建一个新文件(如果有的话)。 So on each time it finds ESTABLISHED , your code deletes old one and creates new one. 因此,每次找到ESTABLISHED ,您的代码就会删除旧代码并创建新代码。

Instead of w use append( a ) mode which will create new file if there isn't one and if there is a file, it will just append your values to the file. 不用w使用append( a )模式,如果没有一个文件并且有文件,它将创建新文件,而是将您的值附加到文件中。

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

You might want to read more from docs on Reading and Writing Files 您可能需要阅读有关读写文件的更多文档

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

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