Reputation: 199
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.
Upvotes: 1
Views: 147
Reputation: 4749
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)
Upvotes: 1