Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách gộp nhiều file thành file mới bằng Python?


Để 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, 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)