如何使用Python将两个文件串联成一个新文件?
要将多个文件合并到一个新文件中,您可以简单地读取文件并使用循环将它们写入新文件。
例如
filenames = ['file1.txt', 'file2.txt', 'file3.txt']with open('output_file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
如果您有非常大的文件,则可以一次一行地写它们,而不是立即写它们。
例如
filenames = ['file1.txt', 'file2.txt', 'file3.txt']with open('output_file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
以上是 如何使用Python将两个文件串联成一个新文件? 的全部内容, 来源链接: utcz.com/z/347240.html