How to save a position in a file while reading it in Python?

Question:

I want to be able to save a reference to a character in a file, then go back to it in the future without iterating through the file. For example, I want to save the reference to X in the following file then in the future, immediately jump to it at a later time without iterating through "nfqo fin qoeif ngo gqowe uzoi asdfjis"

...
nfqo fin qoeif
ngo gqowe uzoi
asdfjis X kajs
...

Then I want to get the character following the marked reference, for example:

saved_reference = X
third_char = saved_reference + 3 # should return 'a'
Asked By: Marty

||

Answers:

As ewong has commented. To save the position of the marker in the file as I reading it, character-by-character, I can use saved_reference = fp.tell() to get the position/reference of the marker. To later jump to it, I do fp.seek(saved_reference). Lastly, if I want to read the third character after it, I first do fp.seek(saved_reference+2), then do f.read(1).

Answered By: Marty
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.