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

这篇具有很好参考价值的文章主要介绍了【python技巧】替换文件中的某几行。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

1. 背景描述

最近在写一个后端项目,主要的操作就是根据用户的前端数据,在后端打开项目中的代码文件,修改对应位置的参数,因为在目前的后端项目中经常使用这个操作,所以简单总结一下。文章来源地址https://www.toymoban.com/news/detail-696381.html

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

到了这里,关于【python技巧】替换文件中的某几行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Python】【完整代码】秀!巧用Python实现对单个文件或多个文件中的指定字符串进行批量修改/替换(超详细)

    目录 1. 对单份文件 1.1 将替换后的内容保存到新文件中 1.2 直接替换当前文件中的字符

    2024年02月21日
    浏览(42)
  • 如何使用pandas读取csv文件中的某一列数据

    使用pandas读取csv文件中的某一列数据,可以这样做: 先导入pandas模块: import pandas as pd 使用 pd.read_csv 函数读取csv文件: df = pd.read_csv(\\\"文件名.csv\\\") 使用 df[\\\"列名\\\"] 读取某一列数据: column = df[\\\"列名\\\"] 例如,如果你有一个csv文件叫做 example.csv ,并且有一列叫做 age ,你可以这样

    2024年02月13日
    浏览(31)
  • python实现对excel表中的某列数据进行排序

    如下需要对webCms中的B列数据进行升序排序, 且不能影响到其他列、工作表中的数据和格式 。 排序后

    2024年02月10日
    浏览(36)
  • 文件名替换,关键字替换改名:不同路径中的多个文件如何批量重命名

    在日常生活和工作中,我们经常需要处理大量的文件,包括重命名、分类、整理等操作。其中,批量重命名不同路径中的多个文件是一项非常常见的任务。本文将介绍云炫文件管理器常见的批量重命名方法:文件名替换改名,帮助您轻松应对不同路径中的多个文件的重

    2024年02月08日
    浏览(58)
  • Python自动化小技巧18——自动化资产月报(word设置字体表格样式,查找替换文字)

    案例背景 每月都要写各种月报,经营管理月报,资产月报.....这些报告文字目标都是高度相似的,只是需要替换为每个月的实际数据就行,如下:   (打码是怕信息泄露.....) 可以看到,这个报告的都是高度模板化,我们只需要对里面的某些文字进行替换,例如2023年7月换成2

    2024年02月12日
    浏览(41)
  • 一键替换工程文件和场景中的UI对象字体

    具体流程: 找到工程中使用到的所有字体 找到工程和场景中包含Text的所有对象 展示要替换的字体名字让用户选择 通过用户选择的字体,展示响应的物体对象 一键替换 通过AssetDatabase.FindAssets找到工程中包含的所有字体:  通过AssetDatabase.FindAssets找到工程中的所有预制体 过

    2024年02月09日
    浏览(30)
  • git提交只单个或者某几个文件的指令

    git status --查看目前本地和远程仓库的差异; git add  \\\' \\\' --提交某的文件,多次执行可以提交多个文件  文件名称替换\\\'\\\' git stash -u -k --其他文件保留到本地暂存区,不进行提交 git commit -m \\\'\\\' ---针对本次修改添加注释并提交到远程仓库 git pull ---拉去远程仓库的代码 git push ---提交

    2024年02月12日
    浏览(30)
  • 掌握文件重命名快捷键,使用替换功能轻松删除文件名中的符号!

    您是否经常面对繁琐的文件重命名工作?是时候掌握一些文件管理的小技巧,让您的工作更加高效便捷了!现在,我们向您介绍一种简单的方法,通过文件重命名快捷键和替换功能,轻松删除文件名中的符号! 首先,我们要打开文件批量改名高手,并在板块栏里选择“文件批

    2024年02月14日
    浏览(25)
  • 在 Python 中替换字典中的值

    使用 dict.update() 方法替换字典中的值,例如 my_dict.update({\\\'key\\\': \\\'new value\\\'}) 。 dict.update() 方法使用提供的值中的键值对更新字典。 我们使用 dict.update 方法来替换字典中的值。 ict.update 方法使用提供的值中的键值对更新字典。 该方法覆盖字典的现有键并返回 None 。 dict.update() 方

    2024年02月07日
    浏览(33)
  • 实用VBA:17.大量word文件中的文本内容进行批量替换

    在工作中可能会遇到需要对大量word文件中的文字内容进行批量替换的情况。相比excel的批量处理,个人感觉word文档中由于包含大量样式信息,批处理时总感觉有顾虑。一者担心影响了文档的格式,误修改了文档的样式,那后果……整过文档的小伙伴都懂的;二者担心批处理不

    2024年01月25日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包