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 replace
calls to:
lines =lines.replace("foo3\n","")
lines = lines.replace("foo5\n","")
Presuming that the exclusions are variable:
def rwfile(infile, outfile, exceptions=[]):
o = open(outfile, "w")
for line in open(infile):
if line.rstrip() not in exceptions:
o.write(line)
o.close()
rwfile("in", "out", ['foo3', 'foo5'])
In:
foo1
foo2
foo3
foo4
foo5
foo6
foo7
foo8
foo9
Out:
foo1
foo2
foo4
foo6
foo7
foo8
foo9
Following on from the OP's comments - here's a version using a predicate function to decide which lines should be included.
def rwfilep(infile, outfile, predicate=lambda x: True):
o = open(outfile, "w")
for line in open(infile):
if predicate(line):
o.write(line)
o.close()
def ignore_some(line):
"""return True to include"""
return line.rstrip() not in ['foo3', 'foo5']
def ignore_comments(line):
"""return True to include"""
return not line.startswith("#")
rwfilep("in", "out2", ignore_some)
rwfilep("in", "out3", ignore_comments)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.