用 Python实现同文件内数据替换案例(欢迎转载)

import re
filename1=open('6548_log0_20200708_01.txt','r') #The source file
filename2=open('6548_log0_20200708_02.txt','a') #Empty file, use to save the result
s_number=''                                                            #the number will be covered 
d_number=''                                                           #the number you want use to insert
s_numbers =[]                                                        #list use to save the all numbers of the line s_number in
d_numbers=[]                                                         #list use to save the all numbers of the line d_number in
#the sign of the number you want to cover IMPORT L03566
s_sign=input('Please input the sign of the number you want to cover:')  
#the sign of the number you want to use to insert INSERT PC_PYMAC_PART_COST
d_sign=input('Please input the sign of the number you want to use to insert:')   

#Read the contents of the sourse file
for line in filename1.readlines():
    if d_sign in str(line):
        #findout the all numbers of this line
        d_numbers = re.findall(r"\d+\.?\d*",str(line))
        #the final number of the list is target
        d_number=str(d_numbers[-1])
    if s_sign in str(line) and d_numbers: 
        #findout the all numbers of this line
        s_numbers=re.findall(r"\d+\.?\d*",str(line))
        #the final number of the list is target
        s_number=str(s_numbers[-1])
        #replace the number
        tt=re.sub(s_number,d_number,line)
        filename2.write(tt)
        continue
    else:
        #insert the content into the filename2
        filename2.write(line)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值