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文件。
极客笔记