简体   繁体   中英

Find and replace certain texts in file using python

I have the following textfile:

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-  

I'm trying to replace the variable LOADLIST = ""; with LOADLIST = "init"; However, only on line 37. My solution so far:

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()

The problem with my code is that it fills the LOADLIST everywhere it finds which means in lines 16,17, 37 & 38 .

Any idea how to filter the search such that only the line 37 is considered? Thanks in advance

Assuming you can't change your txt file to json, if you are looking to only change the LOADLIST that comes after IFSIM, you could use state-fullness to check that the loop has reached 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM