python替换文件中的指定行数技巧示例详解

 更新时间:2023年09月07日 08:47:37   作者:cyl173  
这篇文章主要介绍了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-&gt;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-&gt;ricean_factor  = ')#起点
end_index=file_content.find('chan_desc-&gt;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-&gt;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替换文件中的指定行数技巧示例详解的详细内容,更多关于python替换文件指定行的资料请关注脚本之家其它相关文章!

相关文章

  • Django中Migrate和Makemigrations实操详解

    Django中Migrate和Makemigrations实操详解

    这篇文章主要为大家介绍了Django中Migrate和Makemigrations实操详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • python保存数据到本地文件的方法

    python保存数据到本地文件的方法

    今天小编就为大家分享一篇python保存数据到本地文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • Django进阶之CSRF的解决

    Django进阶之CSRF的解决

    这篇文章主要介绍了Django进阶之CSRF的解决,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • python plotly设置go.Scatter为实线实例

    python plotly设置go.Scatter为实线实例

    这篇文章主要为大家介绍了python plotly设置go.Scatter为实线线条的样式实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • Python使用read_csv读数据遇到分隔符问题的2种解决方式

    Python使用read_csv读数据遇到分隔符问题的2种解决方式

    read.csv()可以从带分隔符的文本文件中导入数据,下面这篇文章主要给大家介绍了关于Python使用read_csv读数据遇到分隔符问题的2种解决方式,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • python SVM 线性分类模型的实现

    python SVM 线性分类模型的实现

    这篇文章主要介绍了python SVM 线性分类模型的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • 在Python中操作文件之read()方法的使用教程

    在Python中操作文件之read()方法的使用教程

    这篇文章主要介绍了在Python中操作文件之read()方法的使用教程,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-05-05
  • Python+matplotlib实现量场图的绘制

    Python+matplotlib实现量场图的绘制

    matplotlib是基于Python语言的开源项目,pyplot提供一系列绘制2D图形的方法。本文将带大家学习matplotlib.pyplot.quiver()相关方法属性并通过其绘制量场图
    2021-12-12
  • Python实现中文大写金额转阿拉伯数字

    Python实现中文大写金额转阿拉伯数字

    在财务票据中,中文大写金额被广泛使用以防止篡改,但在数据处理时,我们需要将其转换为阿拉伯数字形式,下面我们就来看看如何使用Python实现这一转换吧
    2025-08-08
  • python实现决策树分类(2)

    python实现决策树分类(2)

    这篇文章主要介绍了python实现决策树分类的相关资料,用于实际的数据分类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08

最新评论