首页 > 编程语言 >【python技巧】替换文件中的某几行

【python技巧】替换文件中的某几行

时间:2023-09-06 22:31:46浏览次数:45  
标签:index end python 几行 content start file 替换 desc

(【python技巧】替换文件中的某几行)

1. 背景描述

最近在写一个后端项目,主要的操作就是根据用户的前端数据,在后端打开项目中的代码文件,修改对应位置的参数,因为在目前的后端项目中经常使用这个操作,所以简单总结一下。

1. 文件路径:./test.c
2. 文件内容
……
case EPA:
      chan_desc->nb_taps        = 7;
      chan_desc->Td             = .410;
      chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
      sum_amps = 0;
      chan_desc->amps           = (double *) malloc(chan_desc->nb_taps*sizeof(double));
      chan_desc->free_flags=chan_desc->free_flags|CHANMODEL_FREE_AMPS ;

      for (i = 0; i<chan_desc->nb_taps; i++) {
        chan_desc->amps[i]      = pow(10,.1*epa_amps_dB[i]);
        sum_amps += chan_desc->amps[i];
      }

      for (i = 0; i<chan_desc->nb_taps; i++)
        chan_desc->amps[i] /= sum_amps;

      chan_desc->delays         = epa_delays;
      chan_desc->ricean_factor  = 1;//待修改位置
      chan_desc->aoa            = 0;//待修改位置
      chan_desc->random_aoa     = 0;//待修改位置
      chan_desc->ch             = (struct complexd **) malloc(nb_tx*nb_rx*sizeof(struct complexd *));
      chan_desc->chF            = (struct complexd **) malloc(nb_tx*nb_rx*sizeof(struct complexd *));
      chan_desc->a              = (struct complexd **) malloc(chan_desc->nb_taps*sizeof(struct complexd *));
……

2. 单行修改-操作步骤

  1. 读取文件 使用python中的open()函数进行文件读取,将数据存储在缓冲区。
#1. 读取文件
path='./test.c'
with open(path, 'r') as file:
    file_content = file.read()
  1. 查找文件替换位置 以查找chan_desc->ricean_factor = 1;//待修改位置为例,查找这句话的起点和终点。
## 注:此步骤需要import re
#2. 查找文件替换位置
start_index=file_content.find('chan_desc->ricean_factor  = ')#起点
end_index=file_content.find('chan_desc->aoa            = ',start_index)#终点
if end_index==-1 or start_index==-1:
    print('未找到待修改位置')
#此时得到的两个指针,分别指向了待修改位置的起点和终点,如下图所示:

在这里插入图片描述

  1. 设置替换文件内容 假设目前只修改这一行的参数,
#3. 设置替换文件内容
ricean_factor=3#假设这是要修改的参数信息
updata_content=file_content[:start_index]#获取这行代码之前的内容
update_content+='chan_desc->ricean_factor  = '+str(ricean_factor)+';//待修改位置'#修改这行代码
update_content+=file_content[end_index:]#获取这行代码之后的内容
#此时得到的update_content就是修改后的完整文件内容,只修改了ricean_factor这一行的值
  1. 写入文件 同样使用python中的open函数。
#4. 写入文件
if update_content!="":#如果修改内容不为空
    with open(path, 'w') as file:#w表示覆盖写入,之前的内容都会被覆盖
        file.write(update_content)
  1. 总代码 整体的代码如下所示:
import re
#1. 读取文件
path='./test.c'
with open(path, 'r') as file:
    file_content = file.read()
#2. 查找文件替换位置
start_index=file_content.find('chan_desc->ricean_factor  = ')#起点
end_index=file_content.find('chan_desc->aoa            = ',start_index)#终点
if end_index==-1 or start_index==-1:
    print('未找到待修改位置')
#3. 设置替换文件内容
ricean_factor=3#假设这是要修改的参数信息
updata_content=file_content[:start_index]#获取这行代码之前的内容
update_content+='chan_desc->ricean_factor  = '+str(ricean_factor)+';//待修改位置'#修改这行代码
update_content+=file_content[end_index:]#获取这行代码之后的内容
#4. 写入文件
if update_content!="":#如果修改内容不为空
    with open(path, 'w') as file:#w表示覆盖写入,之前的内容都会被覆盖
        file.write(update_content)

3. 多行修改-操作步骤

  1. 多行修改思路 多行修改有两种修改思路,如果修改部分比较集中,则可直接替换一整块的字符串内容,如果修改部分较为分散,则需要单独查找修改位置,然后再分别进行替换。
  2. 多行修改-整块替换
try:
    with open(file_path, "r") as file:
            file_content = file.read()
except Exception as e:
    return str(e)
# 设置改写内容
updated_content = ""
 # 查找修改
start_index_1 = file_content.find("start_sentence")#要确保查找元素的唯一性
end_index_1 = file_content.find("end_sentence",start_index_1,) 

if start_index_1 == -1 or end_index_1 == -1:
    print("未找到待修改位置")
     return -1
 # 
 updated_content = file_content[:start_index_1]#获取这行代码之前的内容
 updated_content += "start_sentence和end_sentence之间的sentence_1;\n"
 updated_content += "start_sentence和end_sentence之间的sentence_2;\n"
 updated_content +=file_content[end_index_1:]

 ##此时updated_content就是修改后的完整文件内容
 if updated_content != "":
     with open(file_path, "w") as file:
         file.write(updated_content)
else:
    print("修改失败")
    return -1
  1. 多行修改-局部替换
try:
    with open(file_path, "r") as file:
            file_content = file.read()
except Exception as e:
    return str(e)
# 设置改写内容
updated_content = ""
 # 查找修改
start_index_1 = file_content.find("start_sentence_1")#要确保查找元素的唯一性
end_index_1 = file_content.find("end_sentence_1",start_index_1,) 
start_index_2 = file_content.find("start_sentence_2",end_index_1)
end_index_2 = file_content.find("end_sentence_2",start_index_2,)
start_index_3 = file_content.find("start_sentence_3",end_index_2)
end_index_3 = file_content.find("end_sentence_3",start_index_3,)
start_index_4 = file_content.find("start_sentence_4",end_index_3)
end_index_4 = file_content.find("end_sentence_4",start_index_4,)

if (
     start_index_1 == -1
     or end_index_1 == -1
     or start_index_2 == -1
     or end_index_2 == -1
     or start_index_3 == -1
     or end_index_3 == -1
     or start_index_4 == -1
     or end_index_4 == -1
 ):
    print("未找到待修改位置")
     return -1

 # 
 updated_content = file_content[:start_index_1]#获取这行代码之前的内容
 updated_content += "start_sentence_1和end_sentence_1之间的内容"
 updated_content +=file_content[end_index_1:start_index_2]
 updated_content += "start_sentence_2和end_sentence_2之间的内容"
 updated_content +=file_content[end_index_2:start_index_3]
 updated_content += "start_sentence_3和end_sentence_3之间的内容"
 updated_content +=file_content[end_index_3:start_index_4]
 updated_content += "start_sentence_4和end_sentence_4之间的内容"
 updated_content += file_content[end_index_4:]

 ##此时updated_content就是修改后的完整文件内容
 if updated_content != "":
     with open(file_path, "w") as file:
         file.write(updated_content)
else:
    print("修改失败")
    return -1

标签:index,end,python,几行,content,start,file,替换,desc
From: https://blog.51cto.com/u_15965807/7391344

相关文章

  • Python 迭代、可迭代对象、迭代器、生成器总结
    迭代对list、tuple、str等类型的数据使用for...in...的循环语法从其中依次拿到数据进行使用,我们把这样的过程称为遍历,也叫迭代可迭代对象不是所有对象都能使用for..in,比如数字10,把可以通过for...in...这类语句迭代读取一条数据供我们使用的对象称之为可迭代对象(Iterable......
  • python-day1
    1.print向文件输出内容A=open('D:/practice.text','a+')print('helloword',file=A)A.close()2.转义字符print('hello\nword')#newlineprint('hello\rword')#return光标移动到本行开头print('hello\bword')#backspaceprint......
  • python分享之读取xml文件(2)
    获得标签属性值<?xmlversion="1.0"encoding="utf-8"?><catalog><maxid>4</maxid><loginusername="pytest"passwd='123456'><caption>Python</caption>......
  • python基础 04数据类型、输出彩色颜色
    数据类型1为什么要有数据类型​ 对于不同类型的变量需要用不同的数据类型去描述​ 常用:数字类型、字符串、列表、字典、布尔值1.1整型作用:年龄/身份证号码/身高/体重……定义方式:y=10id_num=5201314x=int(10)z=int('10')方法:print(y+x)print(y-x)pr......
  • python变量内存的管理
    python变量内存管理当定义一个变量时,内存就会开辟一个内存空间来存储这个变量height=180#定义变量print(180)#print会自动帮你创建一个变量180,打印完成后,马上就会释放180的内存空间引用计数(针对变量值)#引用计数(针对变量值)height=180#180引用计数为1x=height#180......
  • 执行python程序的两种方式
    执行python程序的两种方式方式一:交互式直接win+r打开cmd命令窗口,在里面输入python.exe即可运行此程序直接在命令行窗口里面就能运行python的代码,例如:print(“helloworld!”)优点:运行一句执行一句缺点:关闭即消失方式一:命令行式直接在桌面上新建一个文本文件,在文本文件中写......
  • 《Python魔法大冒险》009 魔法之语:字符串的奥秘
    随着小鱼和魔法师的深入,他们来到了一个被薄雾笼罩的湖泊。湖中央有一个小岛,岛上有一棵巨大的古树,树上挂满了闪闪发光的果实,每一个果实上都刻着一个字母或符号。小鱼好奇地问:“这些是什么果实?为什么每一个上面都有字母和符号?”魔法师微笑地回答:“这些是字符串果实,小鱼。在编程的......
  • Python 迁移虚拟环境
    #在虚拟环境下生成项目依赖文件pipfreeze>requirements.txt#在有网络的环境下载依赖包pipdownload-dpkgs-rrequirements.txt#将txt文件和依赖包pkgs复制到新环境,执行安装pipinstall--no-index--find-links=pkgs-rrequirements.txt#如果有非whl后缀的......
  • 《Python魔法大冒险》 001 序章:少年小鱼的不平凡一天
     在一个普通的城市里,生活着一个名叫小鱼的少年。他是一名初中生,但在班级里,他的学习成绩总是垫底。同学们经常取笑他,有时甚至戏称他为“倒数王”。放学后,小鱼一个人走在回家的路上,他的心情沉重,仿佛背上了一座大山。今天的数学考试又是一场灾难,他甚至怀疑自己是否真的有学习的天......
  • python 变量
    变量什么是变量?变量就是用来变化的世间万物的状态,简单来说就是给他起一个新的代号或名字例如:身高:160,体重:140​ height=160​ print(height)----输出结果就等于160​ ||等价于​ print(160)--------输出结果也等于160​ weight=140​ print(weight)----输出结果......