如何使用 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.