Search code examples
pythonloopstext-filesreadlinedoc

After matching a line, how do I read some more lines and record values, then start over? Python


I am wondering how to search a text document for the word POLYLINE, and then once I find it, how to keep searching the text document for more attributes for POLYLINE, like x coordinates and y coordinates, and then find the next POLYLINE and do it again.

I have a text file that looks like this:

  1. POLYLINE
  2. blah
  3. X coord
  4. fifty
  5. Y coord
  6. sixty three
  7. blah
  8. blah
  9. X coord
  10. ninety
  11. Y coord
  12. six
  13. POLYLINE
  14. And so on...

All my code does so far is find the word POLYLINE, I am stuck trying to collect the attributes of POLYLINE. Here is my code so far:

import re

fileName = open("textdoc.txt, "r")



for line in fileName:
    if re.match("POLYLINE", line):
        print line



fileName.close()

How can I fix this?


Solution

  • for line in fileName:
        if re.match("POLYLINE", line):
            for line in filename:
                if re.match(xcoord,line):
                    dostuff()
                if re.match(ycoord,line):
                    dostuff()
    

    As to how you could actually find the coordinates, it's hard for us to do anything with what you've provided. If there is no pattern as to what line the coordinates will appear in or if there are other numbers that are not your coordinates, and those numbers don't have some sort of identification as such, then there's not much you can do. Basically, find whatever it is that allows you to differentiate the coordinates from anything else, and then just search for that.