首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何合并多个文件?

如何合并多个文件?
EN

Stack Overflow用户
提问于 2016-09-04 08:20:02
回答 1查看 76关注 0票数 0

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

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2016-09-04 08:23:30

只需使用标准库中的fileinput

代码语言:javascript
复制
import fileinput

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

如果您需要对内存使用进行更精细的控制,或者需要处理二进制文件,请使用shutil.copyfileobj

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39312470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档