I need to copy a certain line from a text document, this I have done by using a "key-word" in the document. My problem now is that I also want to copy the entire line below this specific line. Help is much appreciated as I am new with programming

FILE = open('test.txt', 'r')

FILE2 = open('test2.txt', 'w')

for line in FILE.readlines():
if "key-word" in line:
FILE2.write(line)

FILE1.close()
FILE2.close()

Recommended Answers

All 8 Replies

Something like this, with open() close fileobject auto.
If you want line 2 also,change elif to if .

#test.txt
line 1
line 2
line 3 
line 4
f_out = open('outfile.txt', 'w')

flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag:
            f_out.write(line)

f_out.close()
'''Output-->
line 3
line 4
'''

Hello , look at this :) : http://www.daniweb.com/software-development/python/threads/225040

Thanks for the answers!
As I understand this, it will copy all lines below the "key-word", I just want to copy the "key-word" line and the one after in the middle of a text file i.e. I get the position for the line after only by using the "key-word" but I need the data in the line after.

Just reset flag after writing the line out, alternatively:

save = ''
with open('test.txt') as f, open('outfile.txt', 'w') as f_out:
    for line in f:
        if 'line 2' in save:
            f_out.write(line)
        save = line

'''Output-->
line 3
'''

Or "flag = False" after write in my code.
As you se pyTony use only with open ,wicht is an better option.

Or "flag = False" after write in my code.
As you se pyTony use only with open ,wicht is an better option.

Thank you, now it works. I am new to programing but especially new to this "with open('') as".

Can I use the same method to contiue copying lines under e.g. two or three lines under the "key-word"-line?

Can I use the same method to contiue copying lines under e.g. two or three lines under the "key-word"-line?

Yes just pratice with code you have got.
Here something you can look at.

#test.txt
line 1
line 2
line 3 
line 4
line 5
line 6 a keyword
line 7
flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag: #Try if to
            print line.strip()
'''
Output-->
line 3
line 4
line 5
line 6 a keyword
line 7
'''

Next we want to stop at line 6.

flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag:
            print line.strip()
            if 'keyword' in line:
                flag = False
'''Output-->
line 3
line 4
line 5
line 6 a keyword
'''

There are differnt way of doing this as you se i you flag as a start/stop mechanism.

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.