How to read a line in text file, extract substring and return to a column?

Viewed 42

I have this file

                   RTE 001    
  CO. CITY   POSTMILE   PT  POINT                
  ORA DAPT   R000.129   DH  000.102

  ORA DAPT   R000.204   DI
          
  ORA DAPT   R000.231   DH  000.022
  
..........
                   
                   RTE 022

  CO. CITY   POSTMILE   PT  POINT               
  ORA SLB     000.000   DH  000.017
 
  ORA SLB     000.017   DH  000.130 

I would like to have the output like this:

RTE  CO. CITY   POSTMILE   PT  POINT                
001  ORA DAPT   R000.129   DH  000.102
 
001  ORA DAPT   R000.204   DI  
        
001  ORA DAPT   R000.231   DH  000.022

022  ORA SLB     000.000   DH  000.017

022  ORA SLB     000.017   DH  000.130 

I can append the line based on ORA. I don't know how to extract Rte 001, 022 or any number and create a column until the next Rte.

1 Answers
string = ''
with open('file.txt') as file:
    c=False
    for line in file.readlines():
        if 'RTE' in line:
             RTE = line.strip('RTE \n') + ' '

    
    
        elif 'ORA ' in line:
                string +=RTE+line
        elif not c:
            if 'CO.' in line:
                c=True
                string +='RTE '+line

with open('new_file.txt','w') as file:
    file.write(string)
Related