简体   繁体   English

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

[英]Taking the specific column for each line in a txt file python

I have two txt files.我有两个txt文件。 First one is contains a number for each line like this:第一个是每行包含一个数字,如下所示:

22
15
32
53
.
.

and the other file contains 20 continuous numbers for each line like this:另一个文件每行包含 20 个连续数字,如下所示:

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

According to given number in first txt I want to separate the other files.根据第一个 txt 中的给定数字,我想将其他文件分开。 For example, in first txt for first line I have 22, that means I will take first line with 20 column and second line with two column and other columns of second line I will remove.例如,在第一行的第一个 txt 中,我有 22,这意味着我将第一行与 20 列和第二行与两列和第二行的其他列我将删除。 Then I will look second line of first txt (it is 15), that means I will take 15 column from third line of other file and other columns of third line I will remove and so on.然后我会看第一个txt的第二行(它是15),这意味着我将从其他文件的第三行中取出15列,我将删除第三行的其他列,依此类推。 How can I make this?我怎样才能做到这一点?

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:
   ...

Thanks.谢谢。

For the number on each line you iterate through the first file, make that number a target total to read, so that you can use a while loop to keep using next on the second file object to read the numbers and decrement the number of numbers from the total until the total reaches 0. Use the lower number of the total and the number of numbers to slice the numbers so that you output just the requested number of numbers:对于迭代第一个文件的每一行上的数字,将该数字设为要读取的目标总数,以便您可以使用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')

so that given the first file with:以便给定第一个文件:

3
6
1
5

and the second file with:和第二个文件:

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

the output file will have:输出文件将具有:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM