用列表中的值逐行替换文件中符合条件的字符串,并保存为新的文件, open("file").readlines

方案1: 逐行替换并保存为新的文件

import re

def replace_string1():

new_name_list = ["string1", "string11", "string111",...]
# 正则提取
p_s0 = 'def test_TC_(.*?)\('#get accurate String2 at position:def test_TC_String2(
#逐行替换file中String1 with String2
f2 = open("./file_new.py", 'w', encoding='utf-8')
lines = open("./file.py", encoding='utf-8').readlines()

# 逐行查找file中是否包含String2, 找到之后用用列表中的值逐一替换
j = 0
for s in lines:
casename = re.findall(p_s0, s, re.S) #逐行查找file中是是否包含String2, 找到返回列表["String2"], 否则返回[]
if (casename):
while j < len(new_name_list):
s = s.replace(casename[0],new_name_list[j]) # file 行中包含String2, 则替换成列表中的值
j += 1
break

f2.write(s)

f2.close()

方案2: 逐行替换并保存文件

import re
def replace_string2():

with open("./testlistrule.py", 'r+', encoding='utf-8') as f:
content = f.read()

# 正则提取
p_s1 = 'self.case_id = (.*?)\n'
p_s0 = 'def test_TC_(.*?)\('

id = re.findall(p_s1, content, re.S)
casename = re.findall(p_s0, content, re.S)

new_name_list = []
for i in range(len(casename)):
new_casename = casename[i] + "_" + id[i]
new_name_list.append(new_casename)

with open("./testlistrule.py", 'r', encoding='utf-8') as f:
lines = f.readlines()
j = 0
content = []
for s in lines:
casename = re.findall(p_s0, s, re.S)
if (casename):
while j < len(new_name_list):
s = s.replace(casename[0],new_name_list[j])
j += 1
break
content.append(s)
with open("./testlistrule.py", 'w+', encoding='utf-8') as f:
f.write(''.join(content))
f.close()







最新文章

  1. HTTP的报文与状态码
  2. C与C++中的常用提高程序效率的方法
  3. JAVA 一个或多个空格分割字符串
  4. 记录一个mysql按日期分组统计的查询
  5. Jquery用途
  6. delphi XE7 中的消息
  7. html form一点基础知识,实现文件上传
  8. select&amp;pselect/poll&amp;ppoll/epoll
  9. USB状态错误原因
  10. JSTL 格式化输出 Calendar
  11. aix 小机运维
  12. android 计时器,倒计时
  13. wuzhicms 数据迁移策略
  14. hdu 5664 Lady CA and the graph(树的点分治+容斥)
  15. Python学习之--socket续集
  16. scala 小结(一)
  17. 【BZOJ4199】【NOI2015】品酒大会(后缀数组)
  18. 你不可不知的Java引用类型之——强引用
  19. hdu-4738-tarjin/割边
  20. C#_Stream

热门文章

  1. E-MU1212m(E-MU1616m)在Win10(Win11)中的驱动安装
  2. 关于centos8yum源失效问题
  3. 实验四:开源控制器实践——OpenDaylight
  4. 前端框架大比拼:2022年的Vue与React谁更胜一筹?
  5. Docker - Can&#39;t resolve instance hostname.
  6. Jenkins添加代理节点
  7. js实现禁止浏览器后退
  8. wps - Word文档打开后不能编辑
  9. CentOS7 搭建 PXE 安装系统
  10. hyper给linux扩容空间