关于python:python技巧替换文件中的某几行

5次阅读

共计 4614 个字符,预计需要花费 12 分钟才能阅读完成。

TOC

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. 单行批改 - 操作步骤

  1. 读取文件
    应用 python 中的 open()函数进行文件读取,将数据存储在缓冲区。

    #1. 读取文件
    path='./test.c'
    with open(path, 'r') as file:
     file_content = file.read()
  2. 查找文件替换地位
    以查找 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. 设置替换文件内容
    假如目前只批改这一行的参数,

    #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 这一行的值
  4. 写入文件
    同样应用 python 中的 open 函数。

    #4. 写入文件
    if update_content!="":# 如果批改内容不为空
     with open(path, 'w') as file:#w 示意笼罩写入,之前的内容都会被笼罩
         file.write(update_content)
  5. 总代码
    整体的代码如下所示:

    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. 多行批改 - 操作步骤

  6. 多行批改思路
    多行批改有两种批改思路,如果批改局部比拟集中,则可间接替换一整块的字符串内容,如果批改局部较为扩散,则须要独自查找批改地位,而后再别离进行替换。
  7. 多行批改 - 整块替换

    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
  8. 多行批改 - 部分替换

    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
    
正文完
 0