Find and replace certain texts in file using python
Solution 1:
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 a state 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()