2

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?

2
  • 1
    Did you try or search for anything? Commented Jan 22, 2021 at 17:54
  • Read file line by line (split on \n), then for each line split on space. Check if [0] value is variable 2 or 3 using string match (x == 'var...'. then replace [-1] with the desired value. Put them all together. Alternate, use string.find() to search for value, then replace the line as need. I recommend looking at string search options for this Commented Jan 22, 2021 at 18:08

3 Answers 3

3
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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.