簡體   English   中英

使用 python 查找和替換文件中的某些文本

[英]Find and replace certain texts in file using python

我有以下文本文件:

1-   VERSION_CONTROL {
2-   FILE_NAME = "foo.cmp";
3-   REVISION = "";
4-   AUTHOR = "doo";
5-   DATE = "Date: ";
6-   }
7-   
8-   CVTS {
9-   CVTLIST = {
10-   {
11-   CVT = "foo";
12-   }
13-   }
14-   }
15-   IFREAL {
16-   LOADLIST = "";
17-   UNLOADLIST = "";
18-   IOMAPLIST = {
19-   }
20-   }
21-   IFSIM {
22-   SIMULATIONS = {
23-   SIMULATION {
24-   NAME = "";
25-   PROGRAM = "foo.zip";
26-   
27-   RATE = "1";
28-  OFFSET = "0";
29-   SUBFRAME = "0";
30-   LENGTH = "1";
31-   ARGUMENTS = "";
32-   OPTIONS = "RT";
33-   LOOPS = "1";
34-   cpumask = "0";
35-   }
36-   }
37-   LOADLIST = "";
38-   UNLOADLIST = "";
39-   }
40-  

我正在嘗試替換變量LOADLIST = ""; LOADLIST = "init"; 但是,僅在第 37 行。到目前為止,我的解決方案:

reading_file = open(myFile.txt,"r") 
               
               new_file_content = ""
               for line in reading_file:
                   stripped_line = line.strip()
                   new_line = stripped_line.replace('LOADLIST = "";', 'LOADLIST = "initScwss";')
                   new_file_content += new_line +"\n"
               reading_file.close()

               writing_file = open(entry, "w")
               writing_file.write(new_file_content)
               writing_file.close()

我的代碼的問題在於它會在它找到的任何地方填充LOADLIST ,這意味着在第 16,17,37 16,17, 37 & 38行。

知道如何過濾搜索以便只考慮第37行嗎? 提前致謝

假設您無法將 txt 文件更改為 json,如果您只想更改 IFSIM 之后的 LOADLIST,則可以使用 state-fullness 來檢查循環是否已到達 IFSIM。

entry = "outfile.txt"

reading_file = open("myFile.txt","r")

new_file_content = ""
isIfsim = False
for line in reading_file:
    stripped_line = line.strip()
    if "IFSIM" in stripped_line:
        isIfsim = True
    if isIfsim:
        if 'LOADLIST = "";' in stripped_line:
            new_line = stripped_line.replace('LOADLIST = "";', 'LOADLIST = "init";')
            new_file_content += new_line +"\n"
            isIfsim = False
        else:
            new_file_content += stripped_line +"\n"
    else:
        new_file_content += stripped_line +"\n"
reading_file.close()

writing_file = open(entry, "w")
writing_file.write(new_file_content)
writing_file.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM