如何使用 Python 将多个文件合并为一个新文件?
programmingpythonserver side programming
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 文件。