将多个文件合并到一个文件夹中

2024-04-25 09:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为ZebRa的语料库,由7个文件夹组成,每个文件夹内有10个文件。我想合并每个文件夹中的10个文件,以便最终只有7个文件夹。以下是我尝试过的:

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)

但是,每次它清空OutFile的内容时,存储的输出似乎只是最后一个文件夹中最后一个文件的内容 我还尝试了以下操作,但是,输出将是一个空文件:

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())

Tags: 文件pathin文件夹forosrootfiles

热门问题