用Python尝试逐步迭代2个文件

2024-04-26 21:38:58 发布

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

我正在尝试将两个大的输入文件合并到一个输出中,边走边排序。你知道吗

## Above I counted the number of lines in each table

print("Processing Table Lines: table 1 has " + str(count1) + " and table 2 has " + str(count2) )
newLine, compare, line1, line2 = [], 0, [], []

while count1 + count2 > 0:
    if count1 > 0 and compare <= 0: count1, line1 = count1 - 1, ifh1.readline().rstrip().split('\t')
    else: line1 = []
    if count2 > 0 and compare >= 0: count2, line2 = count2 - 1, ifh2.readline().rstrip().split('\t')
    else: line2 = []

    compare = compareTableLines( line1, line2 )
    newLine = mergeLines( line1, line2, compare, tIndexes )

    ofh.write('\t'.join( newLine + '\n'))

我期望发生的是,当行被写入到输出时,我会拉入文件中的下一行(如果可用的话)。我还希望一旦两个文件都为空,循环就会停止。你知道吗

然而,我不断得到这个错误: ValueError:混合迭代和读取方法将丢失数据

我就是不知道该怎么处理。这两个文件都太大,无法保存在内存中,所以我想边读边读。你知道吗


Tags: and文件readlineiftablenewlinecomparesplit
1条回答
网友
1楼 · 发布于 2024-04-26 21:38:58

下面是一个使用^{}^{}合并两个有序文件的示例,在本例中是CSV文件。给定2个CSV文件:

x.csv

key1,99
key2,100
key4,234

y.csv

key1,345
key2,4
key3,45

跑步:

import csv, heapq, itertools

keyfun = lambda row: row[0]

with open("x.csv") as inf1, open("y.csv") as inf2, open("z.csv", "w") as outf:
    in1, in2, out = csv.reader(inf1), csv.reader(inf2), csv.writer(outf)
    for key, rows in itertools.groupby(heapq.merge(in1, in2, key=keyfun), keyfun):
        out.writerow([key, sum(int(r[1]) for r in rows)])

我们得到:

z.csv

key1,444
key2,104
key3,45
key4,234

相关问题 更多 >