textfile: copy between 2 keywords
steve at pearwood.info
Thu Sep 10 14:10:15 CEST 2015
On Thu, 10 Sep 2015 09:18 pm, Gerald wrote:
> is there a easy way to copy the content between 2 unique keywords in a
> .txt file?
> 1, 2, 3, 4
> 3, 4, 5, 6
> 2, 3, 4, 5
> 4, 5, 6 ,7
> Thank you very much
Copy in what sense? Write to another file, or just copy to memory?
Either way, your solution will look something like this:
* read each line from the input file, until you reach the first keyword;
* as soon as you see the first keyword, change to "copy mode" and start
copying lines in whatever way you feel is best;
* until you see the second keyword, then stop.
with open("input.txt") as f:
# Skip lines as fast as possible.
for line in f:
if line == "START\n":
# Instead of copying, I'll just print the lines. That's sort of a copy.
for line in f: # This will pick up where the previous for loop ended.
if line == "STOP\n":
# If you like, you can just finish now.
# Or, we can read the rest of the lines.
for line in f: # continue from just after the STOP keyword.
pass # This is a waste of time...
More information about the Python-list