I have a text file of the format below, and I am trying to edit/update text in the file.
VAR_GROUP
Var1 : DATATYPE1;(Description Var1)
Var2 : DATATYPE2;(Text to be added here)
Var3 : DATATYPE3;(Description Var3)
Var4 : DATATYPE4;(Text to be added here)
END_GROUP
Using Python I am trying to add certain description of for eg., Var3 and Var4. With code I wrote the logic is working fine but the text is added to the end of the file and not at the required position.
def search_write_in_file(file_name, string_to_search, description):
with open(file_name, 'r+') as file_obj:
# Read all lines in the file
for line in file_obj:
# For each line, check if line contains the string
line_number += 1
if (string_to_search in line) and flag_found == 0:
line = line[:-1]+description+'\n'
file_obj.write(line)
flag_found =1
read_obj.close()
Current Output
VAR_GROUP
Var1 : DATATYPE1;(Description Var)
Var2 : DATATYPE2;
Var3 : DATATYPE3;(Description Var3)
Var4 : DATATYPE4;
END_GROUP
Var1 : DATATYPE1;(Description Var1)
Var2 : DATATYPE2;(Description Var2)
Var3 : DATATYPE3;(Description Var3)
Var4 : DATATYPE4;(Description Var4)
What could be the possible reason that the the mentioned specific location is not edited, rather added at the end. Thanks in advance.