Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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)
Posted
Updated 14-Nov-18 22:40pm
v2

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:
Python
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)
 
Share this answer
 
Something similar to
Python
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.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900