Davidson
Davidson

Reputation: 31

Python:Selecting a range of lines from one file and copying it to another file

I have a file and i want to select certain lines in the file and copy it to another file.

In the first file the line where i want to copy has the word "XYZ" and from here i want to select the next 200 lines(including the match line) and copy it to another file.

The below is my code

match_1 = 'This is match word'
with open('myfile.txt') as f1:
     for num, line in enumerate(f1, 1):
        if log_1 in line:
            print line

The above code leads me to the start of the line and i need to select 200 lines form the matched line and then copy,move it to another text file.

I tried couple of options like while statements,but i am not able to build the logic fully.Please help

Upvotes: 1

Views: 1258

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22225

How about something like

>>> with open("pokemonhunt", "r") as f:
...   Lines = []
...   numlines = 5
...   count = -1
...   for line in f:
...     if "pokemon" in line:           % gotta catch 'em all!!!
...       count = 0
...     if -1 < count < numlines:
...       Lines.append(line)
...       count += count
...     if count == numlines:
...       with open("pokebox","w") as tmp: tmp.write("".join(Lines))

Or have I misunderstood your question?

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78554

You can use itertools.islice on the file object once the match is found:

from itertools import islice

# some code before matching line is found
chunk = line + ''.join(islice(f1, 200))

This will consume the iterator f1 to the next 200 lines, and so the num count in your loop may not be coherent if this is placed in your loop.

If you do not need the other lines in the file after finding the match, you can use:

from itertools import islice

with open('myfile.txt') as f1, open('myotherfile.txt') as f_out:
     for num, line in enumerate(f1, 1):
        if log_1 in line:
            break
     chunk = line + ''.join(islice(f1, 200))
     f_out.write(chunk)

Upvotes: 1

Related Questions