简体   繁体   中英

Modify variable value in text file with python

I have a text file with the following content;

variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
variable_4 = 4;

Using python, I would like to modify variable_2 to 22 and variable_3 to 33 such that the text file will look like this;

variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;

How can this be done using python v3.8?

urls = open('variables.txt', 'r')
lines = urls.readlines()  # read all the lines of txt
urls.close()

for index, line in enumerate(lines):  # iterate over each line
    if index == 1:
        line_split = line.split(';')
        line = line_split[0] + '2;\n'
    if index == 2:
        line_split = line.split(';')
        line = line_split[0] + '3;\n'
    lines[index] = line

with open('variables.txt', 'w') as urls:
    urls.writelines(lines)  # save all the lines

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

My answer builds on the answer from Dennis.

Assuming data.txt has following content;

variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;

The code below will solve the problem.

def write_var_to_file(config_file: str, variable_name: str, variable_content: str) -> None:
    from typing import TextIO, List
    urls: TextIO = open(config_file, 'r')
    lines: List[AnyStr] = urls.readlines()  # read all the lines of txt
    urls.close()

    for index, line in enumerate(lines):  # iterate over each line
        line_split: List[str] = line.split('=')
        var_name: str = line_split[0].strip()  # use strip() to remove empty space
        if var_name == variable_name:
            var_value: str = variable_content + ";\n"
            line: str = F"{var_name} = {var_value}"

        lines[index] = line

    with open(config_file, 'w') as urls:
        urls.writelines(lines)  # save all the lines

    return


write_var_to_file(config_file="data.txt", variable_name="variable_2", variable_content="22")
write_var_to_file(config_file="data.txt", variable_name="variable_3", variable_content="33")

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