如何合并多个文件?

2024-06-30 14:06:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文件是txt格式的,我编写了一个简短的代码,将这三个文件合并为一个文件。输入文件为(1)18.8MB,超过16K列;(2)18.8MB,超过16K列;(3)10.5MB,超过7K列。代码可以工作,但是它只合并前两个文件并创建输出文件。不包括来自第三个输入文件的数据。这里有什么问题?txt文件的大小有限制吗?你知道吗

filenames = ['/Users/icalic/Desktop/chr_1/out_chr1_firstset.txt', '/Users/icalic/Desktop/chr_1/out_chr1_secondset.txt', '/Users/icalic/Desktop/chr_1/out_chr1_thirdset.txt']
with open('/Users/icalic/Desktop/chr1_allfinal.txt', 'w') as outfile:
    for fname in filenames:
       with open(fname) as infile:
           for line in infile:
               outfile.write(line)

Tags: 文件代码txtaswithmbopenout
1条回答
网友
1楼 · 发布于 2024-06-30 14:06:31

只需使用标准库中的^{}

import fileinput

filenames = [ '...' ]
with open(output_file, 'w') as file_out, fileinput.input(filenames) as file_in:
    file_out.writelines(file_in)

如果您需要更好地控制内存使用或需要处理二进制文件,请使用shutil.copyfileobj

filenames = [ '...' ]
buffer_length = 1024*1024*10 # 10 MB

with open('output_file.txt', 'wb') as out_file:
    for filename in filenames:
        with open(filename, 'rb') as in_file:
            shutil.copyfileobj(in_file, out_file, buffer_length)

相关问题 更多 >