1

I have a text file that is roughly in this form:

a
  ab
    x: 1 2 3 4 5 6 
a
  ab
    x: 1 4 6 8 243 8 2

That contains thousands of similar style entries per file. I need to strip the numbers out of x into a list in python.

I currently have a text parser that creates a list of the line numbers where x appears, but the parser I have works on the fly, not line by line. Is there a way I can perform an action on the following line of the file without actually being there yet? (IE, my code is executed on line 1, checks that it meets the condition and if so performs an action on line 2 before it continues to check other line conditions.)

All of the numbers are space separated, on a single line with x.

Sam
  • 20,096
  • 2
  • 45
  • 71
  • Would you consider making a new text parser to replace the line-by-line one? If it's not a terribly complicated one, I might recommend it. Where are you getting that text parser from, anyway? – Brōtsyorfuzthrāx Sep 09 '15 at 22:28
  • 1
    I'm using the re module of python and building it from scratch. Im pretty new to this, so I guess I'm looking for an approach where I wont have to make an intermediate text file and write a different script to work with the intermediate file. I'm basically trying to strip out a lot of useless text in between and can't find a good way to deal with it selectively. – Eli Riekeberg Sep 09 '15 at 22:38

1 Answers1

1

I would change your first parser. Instead of doing line by line comparisons how it sounds like you are now, you could do something similar:

Load the whole file into a string. Then, use the split method to turn it into a list. Then you can loop over the list and perform operations on different elements of the list, including on future elements of the list, which are like lines of the text file (although you probably shouldn't delete any elements of the list). Anyway, you can then join it back into a string and save the file.

result=None
with open("myFile.txt", "rb") as FILE: #This is for Python 3.x; for Python 2.x do "r" instead of "rb"
    result=FILE.read()

result_list=result.split("\n")

i=0

while i<len(result_list):
    #Perform your actions here and do result_list[i+1] to get the next line
    i+=1

result="\n".join(result_list)

with open("myFile.txt", "w") as FILE:
    FILE.write(result)

EDIT: The following question/answer might also help you: Reading specific lines only (Python)

Community
  • 1
  • 1
Brōtsyorfuzthrāx
  • 4,387
  • 4
  • 34
  • 56