pythonpython-3.xfile-writing

How to edit a text file at a specific line or location


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.


Solution

  • I'd use regular expressions to match and replace text inside your file

    import re
    
    def search_write_in_file(file_name, string_to_search, description):
        with open(file_name, 'r+') as file_obj:
            text = file_obj.read()
        new_text = re.sub(string_to_search,r"\1 {0}\n".format(description),text)
        with open(file_name, 'w') as file_obj:
            file_obj.write(new_text)
        print(new_text)
    
    if __name__ == '__main__':
        search_write_in_file('text_to_edit.txt',r'(DATATYPE2;\n)',"test2")
        search_write_in_file('text_to_edit.txt',r'(DATATYPE4;\n)',"test4")
    

    This will update the existing file to be

    VAR_GROUP
    Var1 : DATATYPE1;(Description Var)
    Var2 : DATATYPE2; test2
    Var3 : DATATYPE3;(Description Var3)
    Var4 : DATATYPE4; test4
    END_GROUP