【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 命令来完成. 在本教程中,我们将告诉你使用 ...
随机推荐
- [汽车]车架号(VIN)的设计与规范
1 车架号概述 VIN是英文Vehicle Identification Number(车辆识别代码)的缩写,也就是我们平时所说的车架号.大架号. 总共由17位字符组成,是汽车唯一的身份识别信息,好比 ...
- cmd+ssh配置远程服务器Anaconda3_2023+pytorch
一.上传Anaconda3到远程服务器 注意:如果要将这个东西安装在anaconda3文件夹里的话,当前这个目录里不能有这个文件夹.(安的时候会自动创建) 二.安装Anaconda3 1. win+r ...
- 使用CNI网络插件(calico)实现docker容器跨主机互联
目录 一.系统环境 二.前言 三.CNI网络插件简介 四.常见的几种CNI网络插件对比 五.Calico网络之间是如何通信的 六.配置calico让物理机A上的docker容器c1可以访问物理机B上的 ...
- 一分钟学一个 Linux 命令 - find 和 grep
前言 大家好,我是 god23bin.欢迎来到<一分钟学一个 Linux 命令>系列,每天只需一分钟,记住一个 Linux 命令不成问题.今天需要你花两分钟时间来学习下,因为今天要介绍的是 ...
- 使用hashicorp Raft开发分布式服务
使用hashicorp Raft开发高可用服务 开发raft时用到的比较主流的两个库是Etcd Raft 和hashicorp Raft,网上也有一些关于这两个库的讨论.之前分析过etcd Raft, ...
- ABP - 缓存模块(2)
1. 缓存模块源码解析 个人觉得 ABP 分布式缓存模块有三个值得关注的核心点.首先是 AbpRedisCache 类继承了微软原生的 RedisCache,并 通过反射的方式获取RedisCache ...
- 自然语言处理 Paddle NLP - 任务式对话系统-理论
什么是任务型对话: 任务型:用于帮助用户完成某领域的特定任务,例如订餐.查天气.订票等 闲聊型:也称作开放域对话系统,目标是让用户持续的参与到交互过程,提供情感陪伴 问答型:提供知识满足,具体类型比较 ...
- prometheus Histogram 统计原理
大家好,我是蓝胖子,书接上文,我在prometheus描点原理那一篇文章里,留了一个思考题: 我们通常会用到histogram_quantile去计算服务接口时间的耗时情况. histogram_qu ...
- Unity的AssetPostprocessor之Model:深入解析与实用案例 2
Unity AssetPostprocessor中Model相关函数的实际应用 Unity AssetPostprocessor是Unity引擎中的一个重要功能,它可以在导入资源时自动一些脚本,以便对 ...
- Delta Lake_ High-Performance ACID Table Storage over Cloud Object Stores
论文发表于 2020年, 研究数据湖产品的很好的学习资料. 概要 开篇很明确的表明了为什么要做Delta lake这样一个产品. Databricks尝试将数据仓库直接架在云上对象存储之上, 这种尝试 ...