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