首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何按字母顺序连接Python中的多个排序文件?

如何按字母顺序连接Python中的多个排序文件?
EN

Stack Overflow用户
提问于 2014-10-07 15:56:26
回答 1查看 1.7K关注 0票数 4

如何逐行读取多个CSV输入文件,比较每行中的字符,将先按字母顺序出现的行写入输出文件,然后将最小值文件的指针向前推进,继续与所有文件进行比较,直到达到所有输入文件的末尾为止。下面是一些解决方案的粗略计划。

代码语言:javascript
复制
buffer = []

for inFile in inFiles:

    f = open(inFile, "r")
    line = f.next()
    buffer.append([line, inFile])

#find minimum value in buffer alphabetically...
#write it to an output file...

#how do I advance one line in the file with the min value?
#and then continue the line-by-line comparisons in input files?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-07 16:06:41

您可以使用heapq.merge

代码语言:javascript
复制
import heapq
import contextlib

files = [open(fn) for fn in inFiles]
with contextlib.nested(*files):
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))

在Python3.x(3.3+)中:

代码语言:javascript
复制
import heapq
import contextlib

with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(fn)) for fn in inFiles]
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26240228

复制
相关文章

相似问题

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