+3 votes
in Programming Languages by (74.2k points)
edited by
In a folder, I have some contents scattered into multiple smaller files. I want to create one file by copying the contents from those smaller files. How can I do this in Python?

All those smaller files have a common word in their filename.

E.g.

hello_1.txt

hello_2.txt

hello_3.txt

....

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Using functions of Python modules 'os' and 'shutil', you can merge the contents of multiple files into a single file.

Here is an example to copy contents from multiple files having 'hello' in their name to an output file 'final.txt'.

import os
import shutil

with open('final.txt', 'w') as fo:
    # replace 'os.getcwd()' with path to your folder
    for f in os.scandir(os.getcwd()):
        if os.DirEntry.is_file(f) and 'hello' in f.name:
            print("copying data from...{0}".format(f.name))
            shutil.copyfileobj(open(f.name, 'r'), fo)

...