merge multiple files into a single folder

I have corpus named ZebRa consisting of 7 folders, each having 10 files inside. I want to merge the 10 files inside each folder, in order to have finally only 7 folders. Here is what I have tried:

import os
def CombineFiles(file_path):
    with open(file_path, 'r', encoding="utf-8") as f:
        OutFile = open('D:/1.txt', 'w', encoding="utf-8")
        lines = f.read().splitlines()
        for i in range(len(lines)):
            lines[i] = lines[i].replace('\n', '')
        lines.append('\n')
        for i in range(len(lines)):
            OutFile.write(lines[i])
    return OutFile
for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    for filename in files:
        file_path = os.path.join(root, filename)
        CombineFiles(file_path)

However, it seems that each time it empties the content of OutFile and the stored output is only the content of the last file in the last folder I have also tried the following, however, the output will be an empty file:

import os
for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    print(files)
    with open('D:/1.txt', 'w', encoding="utf-8") as OutFile:
        for filename in files:
            file_path = os.path.join(root, filename)
            with open(file_path, 'r', encoding="utf-8") as f:
                OutFile.write(f.read())
728x90

1 Answers merge multiple files into a single folder

Change open('D:/1.txt', 'w', encoding="utf-8") to open('D:/1.txt', 'a', encoding="utf-8"). a flag is used to append new data to end of the file, while the w flag always rewrite the file. See this tutorial.

6 days ago