I am looking to compare to text files and replace matching texts with blanks. My files look like this,
File 1
L1 Abc
L2 HHS
L3 RTY
L4 TYU
L5 678
File 2
L1 Abc
L2 HHS
L3 RTY
L4 TYU
L5 678
L6 HTY
L7 KYU
L8 POI
I need to compare file 1 and file 2 and then replace matching contents in File 1 to be replaced with blanks.
I have written the following code in Python but its not replacing the values. How can I get the desired results. Should I use different approach ? Please advise...
Thanks in Advance.
What I have tried:import re
newcontent: str=''
oldcontent: str=''
with open('C:\Temp\\test1.log', 'r') as content_file:
newcontent = content_file.read()
#print(newcontent)
def replaceData(txt):
with open('C:\Temp\\test2.log', "r") as fout:
oldcontent = fout.read()
print(oldcontent)
print('end of old content....')
a=txt.replace(oldcontent,'')
print(a)
replaceData(newcontent)
解决方案You are trying to replace the complete text of the second file that occurs in the first. But that text does not exist in the first file, only a part of it. You should read the second file line by line and try the replace on just the text of that line. Something like:
import re
newcontent: str=''
oldcontent: str=''
with open('C:\Temp\\test1.log', 'r') as content_file:
newcontent = content_file.read()
#print(newcontent)
def replaceData(txt):
with open('C:\Temp\\test2.log', "r") as fout:
for line in fout:
txt=txt.replace(line,'')
replaceData(newcontent)
Something similar to
with open("test1.log") as f:
f1lin = f.readlines()
with open("test2.log") as f:
f2lin = f.readlines()
f3lin = [s for s in f2lin if not (s in f1lin)]
with open("test3.log", "w+") as f:
f.writelines(f3lin)I suppose.