gEngW
gEngW

Reputation: 19

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

I have two txt files. 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:

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

Upvotes: 1

Views: 237

Answers (1)

blhsing
blhsing

Reputation: 106901

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:

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

Upvotes: 1

Related Questions