Please see my explanation in the code as comments.
Input file (input_file.txt):
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
variable_4 = 4;
Code:
# Open the input and output file in context manager. You can be sure the files will be closed!
with open("input_file.txt", "r") as input_file, open("result.txt", "w") as output_file:
for line in input_file: # Iterate on the lines of input file
splited_line = line.split(" ") # Split the lines on space
if "2;" in splited_line[-1]: # If the last element of list is "2;"
splited_line[-1] = "22;\n" # Chane the last element to "22;\n"
elif "3;" in splited_line[-1]: # If the last element of list is "3;"
splited_line[-1] = "33;\n" # Chane the last element to "33;\n"
# Join the elements of list with space delimiter and write to the output file.
output_file.write(" ".join(splited_line))
Output file (result.txt):
variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;
The code in more compact way:
with open("input_file.txt", "r") as input_file, open("result.txt", "w") as output_file:
for line in input_file:
splited_line = line.split(" ")
splited_line[-1] = "22;\n" if "2;" in splited_line[-1] else splited_line[-1]
splited_line[-1] = "33;\n" if "3;" in splited_line[-1] else splited_line[-1]
output_file.write(" ".join(splited_line))