簡體   English   中英

將多個文件合並到一個文件夾中

[英]merge multiple files into a single folder

我有一個名為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())

open('D:/1.txt', 'w', encoding="utf-8")更改為open('D:/1.txt', 'a', encoding="utf-8") a標志用於新數據添加到文件末尾,而w標志總是重寫文件。 請參閱本教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM