views:

96

answers:

3

Hi everyone,

I have a file where i have multiple records with such data

F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89

now i want to search for the line where if i find length<=50 then delete this line and the next line in the file and write to another file.

Thanks everyone

+1  A: 

From the top of my head:

for every line in file
split by spaces
get last token
split by equal
verify length
write line to another file
delete line and the next

Hope this is what you need to start working.

Tom
+1  A: 

Assuming Python 2.6 (let us know if it's another version you need!), and that you want to skip every line with length <= 50 (and ignore the next line in each case), if any:

import re

def weirdtask(infname, oufname):
  inf = open(infname, 'r')
  ouf = open(oufname, 'w')
  rle = re.compile(r'length=\s*(\d+)')
  for line in inf:
    mo = re.search(line)
    if mo:
      thelen = int(mo.group(1))
      if thelen <= 50:
        next(inf)
        continue
    ouf.write(line)
  ouf.close()

If that's not exactly your specs, please clarify.

  inf.close()
Alex Martelli
A: 

If the columns are always in the same order and there are always the same number, you can just use the .split() method on the string, and find the one you want with an index:

words = line.split()
l = words[4]
temp = l.split("=")[2]
if int(temp) <= 50:
    # found the line, handle it
    do_something_here()

If the columns might be in any order, you could use regular expressions.

s_pat = "length\s*=\s*(\d+)"
pat = re.compile(s_pat)

m = pat.search(line)
if m:
    temp = m.group(1)
    if int(temp) <= 50:
        # found the line, handle it
        do_something_here()

This uses the "match group" from the regular expression to grab the number.

P.S. Two answers appeared while I was writing this. I am not the fastest gun in the west.

steveha
maybe you should move east ?
Tom
Can't afford the stagecoach fare.
steveha