Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

concatenating files in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading