Ismatus3
Junior Poster in Training
78 posts since Dec 2011
Reputation Points: 23
Solved Threads: 2
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
'''
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
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
'''
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Or "flag = False" after write in my code.
As you se pyTony use only with open ,wicht is an better option.
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
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.
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294