Để gộp nhiều file thành file mới, đọc file và ghi vào file mới dùng vòng lặp.
Ví dụ
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())
Nếu file rất lớn, thay vì ghi một lần, ghi từng dòng:
Ví dụ
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)