Reading Formatted files in python -


i have text file looks this:

time: 2014030218  add: india name: sourav   k io res tec e  1 4  3   9   2  2 3  1   4   4  time: 2014030300  add: india name: sourav   k io res tec e  1 3  4   8   3  2 2  2   6   4  3 2  3   6   6 

i want have new file similar skipping add , name information each time step (as common every time step). furthermore, want have rows satisfy restriction on res , tec columns, if 1<=res<=3 , 4<=tec<=7.

so should this.

time: 2014030218   k io res tec e  1 3  1   4   4  time: 2014030300   k io res tec e  1 2  2   6   4  2 2  3   6   6 

note: k serial number.

read each line of file variable line , use tests line.startswith('add: ') , line.startswith('name: ') , skip lines while writing out others. keep track of whether in lines following k io ... line check on actual values (and skip again if appropriate:

with open('input.txt') ifp:     open('output.txt', 'w') ofp:         tec_seen = false         empty_line = false         line in ifp:             start_word = line.split(':', 1)[0]             if start_word in ('add', 'name'):                 continue             if start_word == 'time':                 tec_seen = false             if line.lstrip().startswith('k io res tec e'):                 tec_seen = true                 ofp.write(line)                 continue             if tec_seen , line.strip():                 vals = line.split()                 res = int(vals[2])                 tec = int(vals[3])                 if not 1 <= res <= 3:                     continue                 if not 4 <= tec <= 7:                     continue             else:                 if not line.strip():                     if empty_line:                         continue                     empty_line = true                 else:                     empty_line = false             ofp.write(line) 

Comments