【python技巧】替换文件中的某几行
【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. 单行修改-操作步骤
- 读取文件
使用python中的open()函数进行文件读取,将数据存储在缓冲区。
#1. 读取文件
path='./test.c'
with open(path, 'r') as file:
file_content = file.read()
- 查找文件替换位置
以查找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('未找到待修改位置')
#此时得到的两个指针,分别指向了待修改位置的起点和终点,如下图所示:

- 设置替换文件内容
假设目前只修改这一行的参数,
#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这一行的值
- 写入文件
同样使用python中的open函数。
#4. 写入文件
if update_content!="":#如果修改内容不为空
with open(path, 'w') as file:#w表示覆盖写入,之前的内容都会被覆盖
file.write(update_content)
- 总代码
整体的代码如下所示:
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. 多行修改-操作步骤
- 多行修改思路
多行修改有两种修改思路,如果修改部分比较集中,则可直接替换一整块的字符串内容,如果修改部分较为分散,则需要单独查找修改位置,然后再分别进行替换。 - 多行修改-整块替换
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
- 多行修改-局部替换
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
【python技巧】替换文件中的某几行的更多相关文章
- linux 小技巧(查找替换文件中的ascii编码字符)
这里纪录一些linux下用到的小技巧,以免遗忘 在linux中经常碰见各种文件处理.最常用的就是替换文件中的某些字符.常见字符替换还是很容易完成.但是有些不可见字符以及ascii编码字符等等都无法直接 ...
- 用python 替换文件中的git地址
有个需求要替换文件中git地址,要替换成的git地址是一个变量 本来想用sed替换但是git地址中有斜杠符号 需要转义,提前知道还好弄,如果是变量就不好处理了 #!/usr/bin/python3 # ...
- python逐行读取替换文件中的字符串
用列表中的值逐行替换文件中符合条件的字符串,并保存为新的文件, open("file").readlines 方案1: 逐行替换并保存为新的文件 import re def rep ...
- python操作txt文件中数据教程[4]-python去掉txt文件行尾换行
python操作txt文件中数据教程[4]-python去掉txt文件行尾换行 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文章 python操作txt文件中数据教程[1]-使用pyt ...
- python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件
python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 python操作txt文件中 ...
- python操作txt文件中数据教程[2]-python提取txt文件
python操作txt文件中数据教程[2]-python提取txt文件中的行列元素 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果-将txt中元素提取并保存在c ...
- python操作txt文件中数据教程[1]-使用python读写txt文件
python操作txt文件中数据教程[1]-使用python读写txt文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果 程序实现 filename = '. ...
- linux sed 批量替换文件中的字符串或符号
sed -i :直接修改读取的文件内容,而不是输出到终端. sed -i 就是直接对文本文件进行操作的 替换每行第一次出现的字符串 sed -i 's/查找的字符串/替换的字符串/' 文件 ...
- Python 调用JS文件中的函数
Python 调用JS文件中的函数 1.安装PyExecJS第三方库 2.导入库:import execjs 3.调用JS文件中的方法 Passwd = execjs.compile(open(r&q ...
- 使用 sed 命令查找和替换文件中的字符串的 16 个示例
当你在使用文本文件时,很可能需要查找和替换文件中的字符串.sed 命令主要用于替换一个文件中的文本.在 Linux 中这可以通过使用 sed 命令和 awk 命令来完成. 在本教程中,我们将告诉你使用 ...
随机推荐
- Isito 入门:为什么学 Istio、Istio 是什么
1,Istio 概述 聊聊微服务设计 似乎用上 Kubernetes ,就是微服务系统了. 碰到很多人或公司盲目崇拜 Kubernetes ,一直喊着要上 Kubernetes,但是本身既没有技术储备 ...
- 5月这几个API安全漏洞值得注意!
5月份的一些API安全漏洞报告 希望大家查漏补缺 及时修复自己API可能出现的漏洞 No.1 微软.NET Core漏洞 漏洞详情:微软官方发布公告称,其.NET Core 2.1.3.1和5.0版本 ...
- Quartz + SpringBoot 实现定时任务(多任务,多执行时间)代码模板(直接CV即可)
一,什么是Quartz quartz 是一款开源且丰富特性的Java 任务调度库,用于实现任务调度和定时任务.它支持各种任务类型和灵活的配置选项,具备作业持久化.集群和分布式调度.错误处理和重试机制等 ...
- 三分钟快速了解什么是MES系统
大家好,我是Edison. 近日我打算系统学习和整理一下MES/MOM系统相关的领域知识,从而构建我的业务域知识背景.万丈高楼平地起,我们先从快速了解什么是MES系统开始吧! 作为IT技术从业者,特别 ...
- ELK8.8部署安装并配置xpark认证
ELK8.8部署安装并配置xpark认证 介绍 主要记录下filebeat+logstash+elasticsearch+kibana抽取过滤存储展示应用日志文件的方式:版本基于8.8,并开启xp ...
- 面试官:讲讲MySql索引失效的几种情况
索引失效 准备数据: CREATE TABLE `dept` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `deptName` VARCHAR(30) DEFAUL ...
- 2023-06-29:redis中什么是热点Key?该如何解决?
2023-06-29:redis中什么是热点Key?该如何解决? 答案2023-06-29: 在Redis中,经常被访问的key被称为热点key. 产生原因和危害 原因 热点key问题产生的原因可以归 ...
- PostgreSQL 12 文档: 部分 VIII. 附录
部分 VIII. 附录 目录 A. PostgreSQL错误代码 B. 日期/时间支持 B.1. 日期/时间输入解释 B.2. 处理无效或不明确的时间戳 B.3. 日期/时间关键词 B.4. 日期/时 ...
- IOS开发-UIImageView基本用法
UIImageView是iOS中用于显示图像(图片.gif.svg等)的视图. 它的主要功能有: 1. 显示图片UIImageView可以通过image属性显示一张UIImage类型的图片.可以是本地 ...
- 如何将mp4文件解复用并且解码为单独的.yuv图像序列以及.pcm音频采样数据?
一.初始化解复用器 在音视频的解复用的过程中,有一个非常重要的结构体AVFormatContext,即输入文件的上下文句柄结构,代表当前打开的输入文件或流.我们可以将输入文件的路径以及AVFormat ...