如何使用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)热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短