+3 votes
in Programming Languages by (14.3k 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.






1 Answer

0 votes
by (24.7k points)
edited by

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)