首页 > 解决方案 > 将多个嵌套文件变成一个文件(连接它们)

问题描述

我有一个包含 7 个文件的文件夹,每个文件里面都有几个文本文件。我打算通读它们并将每个嵌套的文本文件写入一个名为 ZebraAllRaw.txt 的文件中。最后,必须只有一个文件包含这 7 个文件中每个文件中存在的所有文本文件。

这是我写的函数:

def CombineFiles(folder):
     with open('D:/ZebraAllRaw.txt', 'a', encoding="utf-8") as OutFile:
        for root, dirs, files in os.walk(folder, topdown= False):
            for filename in files:
                file_path = os.path.join(root, filename)
                with open(file_path, 'r', encoding="utf-8") as f:
                    content = f.read()
                    new_content = content.replace('\n', '')
                    OutFile.write(new_content + "\n")

但是,似乎所有内容都被写入了新文件 9 次,就好像它比预期的要多读一遍。

标签: python

解决方案


确保您不附加来自不同运行的文件。

我只在打开时用write替换了文件模式append

def CombineFiles(folder):
     with open('D:/ZebraAllRaw.txt', 'w', encoding="utf-8") as OutFile: # mode "w", not "a"
        for root, dirs, files in os.walk(folder, topdown= False):
            for filename in files:
                file_path = os.path.join(root, filename)
                with open(file_path, 'r', encoding="utf-8") as f:
                    content = f.read()
                    new_content = content.replace('\n', '')
                    OutFile.write(new_content + "\n")

推荐阅读