1

I have files in a directory and i want to concatenate these files vertically to make a single file.

input

file1.txt   file2.txt
1              8
2              8
3              9

i need output

1
2
3
8
8
9

My script is

import glob
import numpy as np
for files in glob.glob(*.txt):
    print(files)
    np.concatenate([files])

but it doesnot concatenate vertically instead it produces last file of for loop.Can anybody help.Thanks.

manas
  • 479
  • 2
  • 14
  • 2
    Why are you introducing numpy in your code? – C. Pappy Feb 19 '22 at 19:16
  • @C.Pappy i am confused please help.I just want to concatenates the 1d arrays – manas Feb 19 '22 at 19:17
  • Does this answer your question? [Concatenating multiple text files into a single file in Bash](https://stackoverflow.com/questions/2150614/concatenating-multiple-text-files-into-a-single-file-in-bash) (Assuming you are bash. Python/numpy & co are not required for this task, as described). – msanford Feb 19 '22 at 19:43

2 Answers2

1

There's a few things wrong with your code, Numpy appears a bit overkill for such a mundane task in my opinion. You can use a much simpler approach, like for instance:

import glob

result = ""
for file_name in glob.glob("*.txt"):
    
    with open(file_name, "r") as f:
        
        for line in f.readlines():
            result += line
print(result)

In order to save the result in a .txt-file, you could do something like:

with open("result.txt", "w") as f:
    f.write(result)
Bialomazur
  • 1,122
  • 2
  • 7
  • 18
1

This should work.

import glob

for files in glob.glob('*.txt'):
    fileopen = open(r"" + files, "r+")
    file_contents = fileopen.read()
    output = open("output.txt", "a")
    output.write(file_contents)
    output.close()
Whatever
  • 46
  • 5