在txt文件python中为每一行取特定列

时间:2019-03-10 15:22:38

标签: python bash shell

我有两个txt文件。 第一个是每行包含一个数字,如下所示:

22
15
32
53
.
.

另一个文件的每一行包含20个连续数字,如下所示:

0.1 2.3 4.5 .... 5.4
3.2 77.4 2.1 .... 8.1
....
.
.

根据第一个txt中的给定编号,我想分隔其他文件。例如,在第一行的第一txt中,我有22,这意味着我将采用20列的第一行,使用两列的第二行,而第二行的其他列将删除。然后,我将查找第一个txt的第二行(它是15),这意味着我将从其他文件的第三行中取出15列,并从第三行的其他列中删除,依此类推。我该怎么做?

with open ('numbers.txt', 'r') as f:
with open ('contiuousNumbers.txt', 'r') as f2:
with open ('results.txt', 'w') as fOut:
   for line in f:
   ...

谢谢。

1 个答案:

答案 0 :(得分:1)

对于您遍历第一个文件的每一行上的数字,将该数字作为要读取的目标总数,以便您可以使用while循环在第二个文件对象上继续使用next读取数字并从总数中递减数字,直到总数达到0。使用总数中的较小数字和数字来对数字进行切片,以便仅输出所请求的数字:

for line in f:
    output = []
    total = int(line)
    while total > 0:
        try:
            items = next(f2).split()
            output.extend(items[:min(total, len(items))])
            total -= len(items)
        except StopIteration:
            break
    fOut.write(' '.join(output) + '\n')

所以给第一个文件是:

3
6
1
5

,第二个文件带有:

2 5
3 7
2 1
3 6
7 3
2 2
9 1
3 4
8 7
1 2
3 8

输出文件将具有:

2 5 3
2 1 3 6 7 3
2
9 1 3 4 8