0

I am trying to write sample code which will read from a file but a)Ignore empty line b) will only show lines which starts with dm- but its giving me error, not sure what to do , can any one please give me some light

def _find_dm_name():
        with open (IOSTAT_OUTPUT,'r')as f:
                for line in f:
                  lines = (line.rstrip() for line in f)
                  lines = list(line for line in lines if line)
                  if re.match("(dm-)", lines):
                   content=lines
        return content
if __name__ == '__main__':
        dm_name=_find_dm_name()
        print dm_name


Traceback (most recent call last):
  File "test.py", line 47, in <module>
    dm_name=_find_dm_name()
  File "test.py", line 41, in _find_dm_name
    if re.match("(.*)", lines):
  File "/usr/lib64/python2.6/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or buffer

Even though if i try this

def _find_dm_name():

        with open (IOSTAT_OUTPUT,'r')as f:
                for line in f:
                  if re.match("(dm-*)", line):
                   content=line
        return content

it gives me only the last line

but how do I get all the line which match only dm- + ignore any empty lines

alammd
  • 339
  • 4
  • 14
  • You make `lines` a list in the line before the regex, then feed that list to `re.match`. As the error says, it wants a string (or buffer) instead. –  Feb 28 '16 at 22:36
  • `for line in f:` and then the next line `lines = (line.rstrip() for line in f)` is really, really weird. –  Feb 28 '16 at 22:36
  • @Evert , I changes the code , removed list, ( Please see edited section) but now its only give one line (the last line), the rstip.() line i got from bellow link "http://stackoverflow.com/questions/4842057/python-easiest-way-to-ignore-blank-lines-when-reading-a-file" Thanks – alammd Feb 28 '16 at 23:58
  • "it gives me only the last line": because you store every line in the same variable (overwriting its previous value), and then only return that variable at the end. Thus, by that time, `content` only contains the last match. Use a `list` or something and append to it, then return that list if you want to retain all previous matches as well. –  Feb 29 '16 at 03:52

0 Answers0