简体   繁体   English

如何在python中复制文件中的特定行

[英]How to copy the specific lines from file in python

I have a file which contains following lines.In this if i give the input string as "LOG_MOD_L0_RECEIVE_TXBRP_CONTROL" then it should copy the line from 我有一个文件,其中包含以下行。如果我将输入字符串作为“LOG_MOD_L0_RECEIVE_TXBRP_CONTROL”,那么它应该复制该行

6.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)

This is my file: 这是我的档案:

6.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)
7.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_Measure(1, 
 0x0059005m, 
 0x0049006d, 
 0x04b9008b, 
 0x001300b9)

My code: 我的代码:

fo=open("file1.txt","r")
fin=open("file2.txt","r")
string=raw_input("Enter the String:")
lines=fo.readlines()
   for line in lines:
       if string in line:
       fin.write(line)
fin.close()

Its copying only this much. 它的复制只有这么多。

6.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 

it's not copying until the end of close bracket. 它不会复制到关闭括号结束。

You'll have to read the file in chunks; 你必须以块的形式阅读文件; your matching text only appears on one line, but to get the rest of the lines you'll have to continue reading: 您的匹配文本只出现在一行上,但要获得其余行,您必须继续阅读:

with open("file1.txt","r") as fin, open("file2.txt","w") as fout:
    string = raw_input("Enter the String:")
    for line in fin:
        if string in line:
            fout.write(line)
            try: 
                while ')' not in line:
                    line = next(fin)
                    fout.write(line)
            except StopIteration:
                pass  # ran out of file to read

This uses the input file object as an iterable, looping directly over the open file object with for line in fin . 这使用输入文件对象作为可迭代的,直接在打开的文件对象上循环, for line in fin Once a matching line is found, the nested while loop reads more lines from the same file object, until a line with ) is found. 找到匹配的行后,嵌套的while循环会从同一个文件对象中读取更多行,直到找到一行( )

When the for loop then resumes after the while loop completed, the loop picks up where the file object has now progressed to. for循环再后恢复while循环完成后,环弥补了文件对象现在已经进展到。

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

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