【python技巧】替換文件中的某幾行

来源:https://www.cnblogs.com/CrazyPixel/archive/2023/09/06/17683553.html
-Advertisement-
Play Games

# 【python技巧】替換文件中的某幾行 ## 1. 背景描述 最近在寫一個後端項目,主要的操作就是根據用戶的前端數據,在後端打開項目中的代碼文件,修改對應位置的參數,因為在目前的後端項目中經常使用這個操作,所以簡單總結一下。 ``` 1. 文件路徑:./test.c 2. 文件內容 …… cas ...


【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. 單行修改-操作步驟

  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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在vue3中,可以使用vue3的API `defineExpose()`函數結合`ref`或者`$parent`,實現父子組件數據的傳遞。 # 子組件向父組件傳遞數據`defineExpose()`和`ref` - 子組件:通過`defineExpose()` 函數,向外暴露響應式數據或者方法 `` ...
  • 本文給大家介紹了什麼是"編程範式",選擇合適的編程範式可以提高代碼的可讀性、可維護性和可擴展性。 一、 什麼是編程範式? "編程範式"是一種編程思想的總稱,它是指在編寫程式時所採用的基本方法和規範。常見的編程範式有面向對象、函數式、邏輯式等。 選擇合適的編程範式可以提高代碼的可讀性、可維護性和可擴展 ...
  • ### 工廠模式 工廠模式是一種創建者設計模式,細分之下可以分成三類`簡單工廠模式`,`工廠方法模式`和`抽象工廠模式`。 #### 簡單工廠模式 最簡單的工廠模式,它採用靜態方法的方式來決定應該應該生產什麼商品。 ```java public class StoreFactory { public ...
  • 本文與大家一起學習並介紹領域驅動設計(Domain Drive Design) 簡稱DDD,以及為什麼我們需要領域驅動設計,它有哪些優缺點,儘量用一些通俗易懂文字來描述講解領域驅動設計 ...
  • 這篇文章的主要內容包括:1、數據架構的演變歷史與各種架構的優缺點。2、流批一體的價值。3、流批一體架構中流與批的關係。 ...
  • 讓 Java 代碼直接在 Nginx 上運行?這麼有趣的功能,隨本文一起來實戰體驗吧,圖文並茂,一定能成功的那種實戰 ...
  • Starter是SpringBoot的四大核心功能特性之一,除此之外,SpringBoot還有自動裝配,Actuator監控等特性 SpringBoot裡面的這些特性,都是為了讓開發者在開發基於Spring生態下的企業級應用時,只需要關係業務邏輯,減少對配置和外部環境的依賴 ...
  • Linux通常都附帶Python環境,但是Linux附帶的大多數Python都是2.7.5版本。如果我們想使用Python3或者Anaconda3,最好安裝一個新的Python3環境,但不要嘗試刪除Python2,避免引起不必要的麻煩 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...