Python合并文本文件(特定行)

2024-09-30 22:21:49 发布

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

我有两个大的文本文件的数据从一个实验,我想分裂成一个特殊的方式。你知道吗

小样本数据:

文件1:

plotA   10 
plotB   9 
plotC   9

文件2:

98%
7/10
21
98%
5/10
20
98%
10/10
21

我想要这样的结果:

plotA   10  98% 7/10    21
plotB   9   98% 5/10    20
plotC   9   98% 10/10   21

我不知道它是如何在python中解决的。我尝试用以下内容重新排列文件2:

lines = file2.readlines()
aaa = lines[0] + lines[3] + lines[6]
bbb = lines[1] + lines[4] + lines[7]
ccc = lines[2] + lines[5] + lines[8]

和使用zip,但我失败了(这种方法对于大型文本文件来说非常耗时)。你知道吗

有什么帮助吗?你知道吗


Tags: 文件数据方式zipfile2样本linesbbb
2条回答

下面是一个示例,您必须通过错误处理和所有改进:^)

file1 = open('file1')
file2 = open('file2')

# take one line in file1
for line in file1:
        # print result with tabulation to separate fields
        print '\t'.join(
                # the line from file1
                [line.strip()] + 
                # and three lines from file2
                [file2.readline().strip() for _ in '123']
        )       

请注意,我使用的是字符串'123',因为它比range(3)短(而且不需要函数调用);它必须是生成三个步骤的任何类型的iteable。你知道吗

只读取所需的数据并对其进行处理可以避免将所有文件加载到内存中(正如您所说的,您的文件很大)。你知道吗

干杯。你知道吗

您可以使用^{}将文件2分割为三行,然后再次使用它用第一个文件压缩它们:

from itertools import izip_longest
with open('file1.txt') as f1, open('file2.txt') as f2:

     args = [iter(f2)] * 3
     z = izip_longest(f1, izip_longest(*args), fillvalue='-')
     for line, tup in z:
           print '{:11}'.format(line.strip()), '{:5}{:5}{:>5}'.format(*map(str.strip, tup))

如果你想把这个结果写进一个新文件,你可以打开一个文件来写,而不是打印它,把行写进文件。你知道吗

结果:

plotA   10  98%  7/10    21
plotB   9   98%  5/10    20
plotC   9   98%  10/10   21

相关问题 更多 >