1
  1. List item

I have two texts below.

How can I concatenate each line of two files.txt into one filenew.txt?

For example:

file1 includes:

fishenter

tiger

deer

file2 includes:

Roof

today

great

I want the output to be like this:

fishRoof

tigertoday

deergreat

I only know the command to join two files:

cat file1.txt file.txt > filenew.txt

What should the command be?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hai long
  • 11
  • 3
  • 1
    If a bash command is an acceptable answer, please try: `paste -d "" file1.txt file2.txt > filenew.txt`. – tshiono Sep 06 '22 at 03:33

1 Answers1

1

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
Preet Mishra
  • 389
  • 3
  • 7
  • 1
    Just a couple of hint. I'd read the files line by line, avoiding to load the entire files in memory (in this case they are small, but you never know). Moreover, stripping space characters only should be enough: `readlines`, if I'm not wrong, strips the new line for you – Buzz Sep 06 '22 at 04:01
  • thank you, but can you guide me how to get this below command to run on ubuntu terminal hope you understand because I just learned linux ubuntu a few days. – hai long Sep 06 '22 at 08:16
  • You need to save the contents to a `.py` file, for instance, `script.py`, then run it with `python3 script.py`. The output should be in `output.txt`, `cat output.txt` will help. – Preet Mishra Sep 06 '22 at 12:15
  • thanks you million much, so much ,you very good – hai long Sep 13 '22 at 05:09
  • when i do your instruction with small data files it works fine but when i do it with few gigabyte files it gives error like this :root@vultr:~/Downloads# python3 1 .py Killed can you help me, thank you – hai long Sep 14 '22 at 04:56