翼度科技»论坛 编程开发 python 查看内容

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

5

主题

5

帖子

15

积分

新手上路

Rank: 1

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

1. 背景描述

最近在写一个后端项目,主要的操作就是根据用户的前端数据,在后端打开项目中的代码文件,修改对应位置的参数,因为在目前的后端项目中经常使用这个操作,所以简单总结一下。
  1. 1. 文件路径:./test.c
  2. 2. 文件内容
  3. ……
  4. case EPA:
  5.       chan_desc->nb_taps        = 7;
  6.       chan_desc->Td             = .410;
  7.       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));
  8.       sum_amps = 0;
  9.       chan_desc->amps           = (double *) malloc(chan_desc->nb_taps*sizeof(double));
  10.       chan_desc->free_flags=chan_desc->free_flags|CHANMODEL_FREE_AMPS ;
  11.       for (i = 0; i<chan_desc->nb_taps; i++) {
  12.         chan_desc->amps[i]      = pow(10,.1*epa_amps_dB[i]);
  13.         sum_amps += chan_desc->amps[i];
  14.       }
  15.       for (i = 0; i<chan_desc->nb_taps; i++)
  16.         chan_desc->amps[i] /= sum_amps;
  17.       chan_desc->delays         = epa_delays;
  18.       chan_desc->ricean_factor  = 1;//待修改位置
  19.       chan_desc->aoa            = 0;//待修改位置
  20.       chan_desc->random_aoa     = 0;//待修改位置
  21.       chan_desc->ch             = (struct complexd **) malloc(nb_tx*nb_rx*sizeof(struct complexd *));
  22.       chan_desc->chF            = (struct complexd **) malloc(nb_tx*nb_rx*sizeof(struct complexd *));
  23.       chan_desc->a              = (struct complexd **) malloc(chan_desc->nb_taps*sizeof(struct complexd *));
  24. ……
复制代码
2. 单行修改-操作步骤


  • 读取文件
    使用python中的open()函数进行文件读取,将数据存储在缓冲区。
  1. #1. 读取文件
  2. path='./test.c'
  3. with open(path, 'r') as file:
  4.     file_content = file.read()
复制代码

  • 查找文件替换位置
    以查找chan_desc->ricean_factor  = 1;//待修改位置为例,查找这句话的起点和终点。
  1. ## 注:此步骤需要import re
  2. #2. 查找文件替换位置
  3. start_index=file_content.find('chan_desc->ricean_factor  = ')#起点
  4. end_index=file_content.find('chan_desc->aoa            = ',start_index)#终点
  5. if end_index==-1 or start_index==-1:
  6.     print('未找到待修改位置')
  7. #此时得到的两个指针,分别指向了待修改位置的起点和终点,如下图所示:
复制代码


  • 设置替换文件内容
    假设目前只修改这一行的参数,
  1. #3. 设置替换文件内容
  2. ricean_factor=3#假设这是要修改的参数信息
  3. updata_content=file_content[:start_index]#获取这行代码之前的内容
  4. update_content+='chan_desc->ricean_factor  = '+str(ricean_factor)+';//待修改位置'#修改这行代码
  5. update_content+=file_content[end_index:]#获取这行代码之后的内容
  6. #此时得到的update_content就是修改后的完整文件内容,只修改了ricean_factor这一行的值
复制代码

  • 写入文件
    同样使用python中的open函数。
  1. #4. 写入文件
  2. if update_content!="":#如果修改内容不为空
  3.     with open(path, 'w') as file:#w表示覆盖写入,之前的内容都会被覆盖
  4.         file.write(update_content)
复制代码

  • 总代码
    整体的代码如下所示:
  1. import re#1. 读取文件
  2. path='./test.c'
  3. with open(path, 'r') as file:
  4.     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. 写入文件
  5. if update_content!="":#如果修改内容不为空
  6.     with open(path, 'w') as file:#w表示覆盖写入,之前的内容都会被覆盖
  7.         file.write(update_content)
复制代码
3. 多行修改-操作步骤


  • 多行修改思路
    多行修改有两种修改思路,如果修改部分比较集中,则可直接替换一整块的字符串内容,如果修改部分较为分散,则需要单独查找修改位置,然后再分别进行替换。
  • 多行修改-整块替换
  1. try:
  2.     with open(file_path, "r") as file:
  3.             file_content = file.read()
  4. except Exception as e:
  5.     return str(e)
  6. # 设置改写内容
  7. updated_content = ""
  8. # 查找修改
  9. start_index_1 = file_content.find("start_sentence")#要确保查找元素的唯一性
  10. end_index_1 = file_content.find("end_sentence",start_index_1,)
  11. if start_index_1 == -1 or end_index_1 == -1:
  12.     print("未找到待修改位置")
  13.      return -1
  14. #
  15. updated_content = file_content[:start_index_1]#获取这行代码之前的内容
  16. updated_content += "start_sentence和end_sentence之间的sentence_1;\n"
  17. updated_content += "start_sentence和end_sentence之间的sentence_2;\n"
  18. updated_content +=file_content[end_index_1:]
  19. ##此时updated_content就是修改后的完整文件内容
  20. if updated_content != "":
  21.      with open(file_path, "w") as file:
  22.          file.write(updated_content)
  23. else:
  24.     print("修改失败")
  25.     return -1
复制代码

  • 多行修改-局部替换
  1. try:
  2.     with open(file_path, "r") as file:
  3.             file_content = file.read()
  4. except Exception as e:
  5.     return str(e)
  6. # 设置改写内容
  7. updated_content = ""
  8. # 查找修改
  9. start_index_1 = file_content.find("start_sentence_1")#要确保查找元素的唯一性
  10. end_index_1 = file_content.find("end_sentence_1",start_index_1,)
  11. start_index_2 = file_content.find("start_sentence_2",end_index_1)
  12. end_index_2 = file_content.find("end_sentence_2",start_index_2,)
  13. start_index_3 = file_content.find("start_sentence_3",end_index_2)
  14. end_index_3 = file_content.find("end_sentence_3",start_index_3,)
  15. start_index_4 = file_content.find("start_sentence_4",end_index_3)
  16. end_index_4 = file_content.find("end_sentence_4",start_index_4,)
  17. if (
  18.      start_index_1 == -1
  19.      or end_index_1 == -1
  20.      or start_index_2 == -1
  21.      or end_index_2 == -1
  22.      or start_index_3 == -1
  23.      or end_index_3 == -1
  24.      or start_index_4 == -1
  25.      or end_index_4 == -1
  26. ):
  27.     print("未找到待修改位置")
  28.      return -1
  29. #
  30. updated_content = file_content[:start_index_1]#获取这行代码之前的内容
  31. updated_content += "start_sentence_1和end_sentence_1之间的内容"
  32. updated_content +=file_content[end_index_1:start_index_2]
  33. updated_content += "start_sentence_2和end_sentence_2之间的内容"
  34. updated_content +=file_content[end_index_2:start_index_3]
  35. updated_content += "start_sentence_3和end_sentence_3之间的内容"
  36. updated_content +=file_content[end_index_3:start_index_4]
  37. updated_content += "start_sentence_4和end_sentence_4之间的内容"
  38. updated_content += file_content[end_index_4:]
  39. ##此时updated_content就是修改后的完整文件内容
  40. if updated_content != "":
  41.      with open(file_path, "w") as file:
  42.          file.write(updated_content)
  43. else:
  44.     print("修改失败")
  45.     return -1
复制代码
来源:https://www.cnblogs.com/CrazyPixel/p/17683553.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具