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.

3
  • 2
    Why are you introducing numpy in your code? Commented Feb 19, 2022 at 19:16
  • @C.Pappy i am confused please help.I just want to concatenates the 1d arrays Commented Feb 19, 2022 at 19:17
  • Does this answer your question? 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). Commented Feb 19, 2022 at 19:43

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

can you please suggest how to save it to a text file?
sure, I'll update the answer quickly for you.
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()

2 Comments

can you please suggest how to save it to a text file
@bijay edited answer to save to file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.