Search code examples
pythontextread-write

Replace Data and Read Write in Text File


I wanna make the editing processes to the input text file and rewrite the result as "new text file". In my case, I have and "input.txt" and "template.txt" as of the following. I wanna rewrite "template.txt" depending on "input.txt" data by "python".

  1. I wanna skip the lines starting with # in "template.txt"
  2. Relace "BKUP" with the data in "input.txt" Could you please help me?

input.txt

ACTUAL

IN USE

NOT TESTING

template.txt

#It is the template.

This is BKUP.

#Thanks

template.txt (Rewrite : Expected Output)

This is ACTUAL.

This is IN USE.

This is NOT TESTING.


Solution

  • You have 3 files:

    input.txt

    ACTUAL
    
    IN USE
    
    NOT TESTING
    

    template.txt

    #It is the template.
    
    This is BKUP.
    
    #Thanks
    

    main.py

    #read the lines of the template file
    with open("template.txt", "r") as file:
        template_lines = file.readlines()
    
    #read the inputs
    with open("input.txt", "r") as file:
        inputs = list(set(filter(lambda x:x!='', map(lambda x:x.rstrip().strip(), file.readlines()))))
    
    # the line of the input chosen
    chosen_input_index = 1
    
    def print_inputs(inputs_list):
        for i, input_ in enumerate(inputs_list):
            print(f"{i}) {input_}")
    
    # open and write the template file
    with open("template.txt", "w") as file:
        # join the template lines in a text variable
        txt_template = "".join(template_lines)
        for i,line in enumerate(template_lines):
            if "BKUP" in line:
                print(f"Editing line num: {i}")
                print_inputs(inputs)
                # wait for an input from the user for the input line index
                inp = -1
                while inp not in range(len(inputs)):
                    inp = input(">>> ")
                    try: inp = int(inp)
                    except: inp = -1
    
                # replace the next BKUP with the chosen input
                txt_template = txt_template.replace("BKUP", inputs[inp])
        # write back the edited template in the template.txt file
        file.write(txt_template)
    

    Hope this helps.

    EDIT: intro text is for the "to edit line"

    intro_text = "This is "
    # open and write the template file
    with open("template.txt", "w") as file:
        inputs_edited = "\n".join([intro_text+input_+"." for input_ in inputs])+ "\n"
        template_lines = list(map(lambda x: inputs_edited if "BKUP" in x else x, template_lines))
        file.write(''.join(template_lines))
    

    if u wanna remove the lines with # do this when opening the template:

    with open("template.txt", "r") as file:
        template_lines = list(filter(lambda x: "#" not in x, file.readlines()))
    

    if u wanna put the same input more times remove the list(set( from the "read input"