python修改文件内容_Python替换文件中的匹配内容

1586010002-jmsa.png

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值