contactenate two line in one in a text file in python

To concatenate two lines in a text file using Python, you can read the file line by line, and for each two consecutive lines, concatenate them into one line. Here's an example code:

main.py
# open the input file
with open('input.txt', 'r') as f_input:
    # open the output file
    with open('output.txt', 'w') as f_output:
        # initialize the current line variable
        current_line = ''
        # loop through the input file line by line
        for line in f_input:
            # remove the newline character from the line
            line = line.rstrip('\n')
            # concatenate the line with the previous line
            concatenated_line = current_line + line
            # write the concatenated line to the output file
            f_output.write(concatenated_line + '\n')
            # update the current line variable
            current_line = line
685 chars
17 lines

In this example, we read the input file ('input.txt') and opened the output file ('output.txt') for writing. Then, we looped through the input file line by line, removed the newline character ('\n') from each line, concatenated it with the previous line, and wrote the concatenated line to the output file. Finally, we updated the current line variable with the current line, so that we can concatenate it with the next line in the next iteration.

gistlibby LogSnag