#!/usr/bin/python
#coding=utf8
# 用替换文件里的内容 替换掉 源文件中 指定的字符串(正则匹配),生成目标文件(新文件)
import re
try:
count = 0 ##记录替换次数
f_rep = open("C:\\Users\\harol\\Downloads\\替换文件.txt", 'r', encoding='utf-8') # 需要替换的字符文件
f_older = open("C:\\Users\\harol\\Downloads\\被替换文件.txt", 'r+', encoding='utf-8') ## 被替换的源文件(模板等)
f_new = open("C:\\Users\\harol\\Downloads\\新文件.txt", 'w+', encoding='utf-8') ## 打开文件 (替换后的新文件)
order_read = f_older.read() ##被替代文件字符串
pat = re.compile("(3[a-zA-Z0-9]{9})") ## 正则匹配被替代文件
order_list = pat.split(order_read) ## 文件被目标字符分割
m1 = pat.findall(order_read) ## 目标列表
lines = f_rep.readlines() ## 替代文件内容列表
line =[]
for lin in lines:
lin = lin.strip()
line.append(lin) ## 去除替代文件列表的换行符
while count < len(m1) and count< len(line):
order_list[2*count+1]=line[count] ## 替换新的文件列表
count += 1
l_new = ''.join(order_list) ## 列表转换为字符串
f_new.write(l_new) ## 字符串写入文件
print(l_new)
except Exception as e:
print(e)
finally:
f_rep.close()
f_older.close()
f_new.close() ## 关闭文件
print(count)