Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python2.7中,合并数百个按2个键排序的文件_Python_Python 2.7_Sorting - Fatal编程技术网

在Python2.7中,合并数百个按2个键排序的文件

在Python2.7中,合并数百个按2个键排序的文件,python,python-2.7,sorting,Python,Python 2.7,Sorting,我有数百个文本文件,其中的数据格式为(id1,id2,value): 每个文本文件中的数据按id1排序,然后按id2排序。字段在每行末尾用“\n”进行制表符分隔。它很大:每个文件有500000行,数百个文件无法合并到内存中。[我自己生成文本数据文件,因此可以更改格式或每个文件的行数,如果这样做可以使事情更简单。] 在Python3.5中有一个关键函数,但是顺便说一句,Python2.7中没有 在Python2.7中,有什么有效的方法可以将这数百个已排序的文件合并成一个大文本文件,格式相同(id1

我有数百个文本文件,其中的数据格式为(id1,id2,value):

每个文本文件中的数据按id1排序,然后按id2排序。字段在每行末尾用“\n”进行制表符分隔。它很大:每个文件有500000行,数百个文件无法合并到内存中。[我自己生成文本数据文件,因此可以更改格式或每个文件的行数,如果这样做可以使事情更简单。]

在Python3.5中有一个关键函数,但是顺便说一句,Python2.7中没有

在Python2.7中,有什么有效的方法可以将这数百个已排序的文件合并成一个大文本文件,格式相同(id1 id2 value),数据先按id1排序,然后按id2排序

注意:我不知道为什么,但是Python将数字排序为字符串,所以我不得不强制它解释为数字。为了解决这个问题,我使用以下
itertools.imap
per:

infiles=['file1.txt','file2.txt',…,'file592.txt']
文件=[为内嵌中的fn打开(fn)]
使用contextlib.nested(*文件):
将open('Results.txt','w')作为f:
#f、 与写入线(heapq.merge(*文件))相关的:
1050 20482 25
9582 92883 48
2750275 28032 3
infiles = ['file1.txt','file2.txt',...,'file592.txt']
files = [open(fn) for fn in infiles]
with contextlib.nested(*files):
    with open('Results.txt', 'w') as f:
    #f.writelines(heapq.merge(*files))  <<<--- the standard way
    for line in map(str, heapq.merge(*(itertools.imap(int, file) for file in files))): #<<<--- forces ids to be sorted as integers 
        f.write(line+'\n')