How to marge current line with previous line in txt file based on some condition in python?

My input text file is :

enter image description here

My expected output text file is : enter image description here

Here we need to merge line 3 and 4 based on the condition that line 4 is not starting with "[" using python


Loop through lines, keep previous line in a variable.

If current line doesn't start with [, add it to the previous line.

Else save previous line to file and update it.


You can try something along the following lines:

lines = []

with open("file_in.txt") as f_in:
    for line in f_in:
        if line.startswith("["):
            lines.append(line)
        else:
            lines[-1] += line  # append to last line

with open("file_out.txt", "w") as f_out:
     f_out.writelines(lines)