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

时间:2019-03-14 00:58:21

标签: python file

我有一个名为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())

1 个答案:

答案 0 :(得分:0)

open('D:/1.txt', 'w', encoding="utf-8")更改为open('D:/1.txt', 'a', encoding="utf-8")a标志用于将新数据附加到文件末尾,而w标志始终重写文件。参见此tutorial