如何使用 Python 將多個檔案合併到一個新檔案中?


Python 使建立新檔案、讀取現有檔案、追加資料或替換現有檔案中的資料變得簡單。藉助一些開源和第三方庫,它可以管理當前支援的幾乎所有檔案型別。

為了將多個檔案連線到單個檔案中,我們必須遍歷所有必需的檔案,收集其資料,然後將其新增到新檔案中。本文演示瞭如何使用 Python 將多個檔案連線到單個檔案中。

使用迴圈

在下面的 Python 程式碼中,可以找到所需 python 檔案的檔名或檔案路徑列表。接下來,開啟或建立 advanced_file.py。

然後迭代檔名或檔案路徑列表。每個檔案都會生成一個檔案描述符,逐行讀取其內容,然後將資料寫入 advanced_file.py 檔案。

它在每行末尾在新檔案中新增換行符或 \n。

示例 - 1

以下是如何使用 for 迴圈將多個檔案合併到單個檔案的示例:

nameOfFiles = ["moving files.py", "mysql_access.py", "stored procedure python-sql.py", "trial.py"] with open("advanced_file.py", "w") as new_created_file: for name in nameOfFiles: with open(name) as file: for line in file: new_created_file.write(line) new_created_file.write("\n")

輸出

作為輸出,將建立一個名為“advanced_file”的新 python 檔案,其中包含所有提到的現有 python 檔案。

示例 - 2

在以下程式碼中,我們以讀取模式打開了現有檔案,並以寫入模式打開了新建立的檔案,即 advanced_file。之後,我們從這兩個檔案中讀取資料並將其新增到字串中,並將資料從字串寫入新建立的檔案。最後,關閉檔案:

info1 = info2 = "" # Reading information from the first file with open('mysql_access.py') as file: info1 = file.read() # Reading information from the second file with open('trial.py') as file: info2 = file.read() # Merge two files for adding the data of trial.py from next line info1 += "\n" info1 += info2 with open ('advanced_file.py', 'w') as file: file.write(info1)

輸出

作為輸出,將建立一個名為“advanced_file”的新 python 檔案,其中包含所有提到的現有 python 檔案。

更新於:2022年8月18日

12K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.