I have a text file (file1.txt) with 1 string per line over many lines.
I’m trying to read in the file and write certain lines to a new file.(file2.txt)
My text file looks something like this.
foo1
foo2
foo3
foo4
foo5
foo6
etc..
for example, i want to write foo1,foo2,foo4,foo6 to my new file and miss out foo3 and foo5.
foo1
foo2
foo4
foo6
I wish to preserve the original file.
My code looks like this…
with open("file1.txt","r") as r:
lines=r.read()
lines =lines.replace("foo3","")
lines = lines.replace("foo5","")
r.close()
with open("file2.txt","a") as w:
w.write(lines)
w.close
The problem is I end up with this output..
foo1
foo2
foo4
foo6
I think this is because i am replacing foo with “”
how do I get rid of the white space?
TIA,
Paul.
The minimal change is to also replace the line separators by changing the
replacecalls to: