How to copy the specific lines from file in python

Question:

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

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.

Asked By: user3082400

||

Answers:

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. Once a matching line is found, the nested while loop reads more lines from the same file object, until a line with ) is found.

When the for loop then resumes after the while loop completed, the loop picks up where the file object has now progressed to.

Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.