pythonvisual-studioterminal

How to save specific split of output from terminal in text file using python VS code in linux?


For example, the output from the terminal is:

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

(the numbers are purely random and there are unlimited lines not just 5, you can see the picture): 1

And i want to save all the numbers in the second split which are

2
3
2
2
4

in a text file. So far i only learned how to write all the output, but i have no idea of how to save the specific split i want. Can anyone help? Thanks in advance!


Solution

  • First save the ouput in a text file and then send it possible. Based on image what you can try is save in a .txt while runuing a comman dlike so.

    your_command > input.txt
    

    Then it will saved to a file.

    with open('input.txt', 'r') as file:
        numbers = []
        for line in file:
            if '=>' in line:                  
                parts = line.split('=>')[1].strip().split()
                if len(parts) >= 2:
                    numbers.append(parts[1])  
    
    
    with open('output.txt', 'w') as file:
        for number in numbers:
            file.write(number + '\n')