I am currently writing an script which is replacing the line of a file with the content of two other files and right after writes the new line to a new file. But when running my script only the content of the first file was replaced with the content of the line.
with open('file1.txt','r') as file1, open('file2.txt','r') as file2, open('original.txt','r') as original: for lines in original: with open('sample.txt','w') as sample: for line in file1: sample.write(lines.replace(line,'')) sample.close() with open('sample.txt','w') as sample: for line in file2: sample.write(lines.replace(line,'')) sample.close()
Content of my file1:
Content of my file2:
Content of my original file:
I Python like Pascal cookies
Content of the new file after running my script:
I like Pascal cookies
What the content of the new file should actually look like after running my script:
I like cookies
Am I doing something wrong? Could someone tell me what’s wrong and help solve this problem?
The problem that your
replaces are targeting always to the original value,
lines so your multiple changes do not accumulate.
So for example
a = 'ciao' a.replace('i', 'I') print(a)
ciao since replace return a new string (strings are immutable) object which you need to store in some variable otherwise… just useless
Here a solution
with open('./file1','r') as file1, open('./file2','r') as file2, open('original','r') as original: with open('sample.txt','w') as sample: a = original.read() b = a.replace(file1.read(), '') c = b.replace(file2.read(), '') sample.write(c) with open('sample.txt', 'r') as fd: print(fd.read())
I like cookies