Reputation: 3
I am trying to copy a specific part of a file to another one. The input file has four lines which start by the same name ("1" in the example given). I don't know exactly how I could take only the part of the file that is between the first "1" and the second "1" (more than 100 lines...):
· · 1 · · · 1 · · · 1
I just started the following:
f_read = open(pathway, "r")
f_write = open(pathway, "w")
cnt = 0
with f_read as f1:
for line in f1:
if line.startswith("1"):
cnt =+ 1
if cnt == 2:
break
And here I do not know how to specify the part of the file I want (from the first "1" until the second "1")...
Any ideas? Thank you in advance!!
Upvotes: 0
Views: 102
Reputation: 180550
You should use with to open both files. In your code if pathway is actually the same file you immediately open pathway
to write after opening it to read so you are basically going to try to iterate over an empty file. You should use a temporary file to write to and then update the original if required.
with open(pathway) as f_read, open("temp_out.txt", "w") as f_write:
for line in f_read:
if line.startswith("1")
for wanted_line in f_read:
# work on wanted lines
if wanted_line.startswith("1"):
break
with open("temp_out.txt", "w") as f_in, open(pathway, "w") as f_out:
for line in f_in:
f_out.write(line)
Upvotes: 0
Reputation: 215059
Basically,
for line in in_file:
if line.startswith('1'):
break
for line in in_file:
if line.startswith('1'):
break
<do stuff>
This uses the fact that python iterators are stateful, and the second loop starts where the first one has stopped, not from the beginning.
Upvotes: 1