how to concatenate each line of 2 file.txt into one filenew.txt

Viewed 57
  1. List item

I have 2 texts below how to concatenate each line of 2 files.txt into one filenew.txt for example : file1 includes:

fishenter

tiger

deer

file2 includes:

Roof

today

great

I want output like this:

fishRoof

tigertoday

deergreat

I only know the command to join 2 files

cat file1.txt file.txt> filenew.txt

please edit the command for me thank you so much

1 Answers

This needs three files to process: two input files and an output file. The first two would be in the "read", the default, mode while the latter would in "write".

We could read the files line by line with .readlines.

To merge them, we could write the two words next to each other. zip would read the two words from the two input files in pair.

Note that we would need to trim/strip any extra whitespace from the words.

An additional \n is there to add a newline.

with open("file1.txt") as f1, open("file2.txt") as f2, open("output.txt", "w") as f3:
    file1_lines = f1.readlines()
    file2_lines = f2.readlines()
    
    for file1_line, file2_line in zip(file1_lines, file2_lines):
        file1_line = file1_line.strip(" \n")
        file2_line = file2_line.strip(" \n")

        # If either of the word is empty, do not write it. This could be modified as per the use case.
        if not file1_line or not file2_line:
            continue

        f3.write(f"{file1_line}{file2_line}\n") # Extra whitespace could be added as per the need.

Output

fishRoof
tigertoday
deergreat
Related