Ai Chan
Ai Chan

Reputation: 33

Pointer position does not start from 0

i want to ask about tell() method. So, have code like this

op = open('data.txt', 'r')
pos = op.tell()
data = op.readline()
key = []
while data:
   pos = op.tell()
   data = op.readline()
   key.append(pos)

and the result

key[:3]
[[87], [152], [240]]

i want my key value start from 0 since it's the first pointer position for the beginning of the sentence. but it starts from the starting pointer value for 2nd sentence. sorry, i'm new to python.

the data looks like this. it's containing few rows

  Sanjeev Saxena#Parallel Integer Sorting and Simulation Amongst CRCW Models.
  Hans Ulrich Simon#Pattern Matching in Trees and Nets.
  Nathan Goodman#Oded Shmueli#NP-complete Problems Simplified on Tree Schemas.

Upvotes: -1

Views: 138

Answers (2)

Zubda
Zubda

Reputation: 963

In the comments I realized our mistake... The while data condition requires you to have read a chunk of text, I think the correct way will be to use a while True loop and break on completion.

# list to store results.
keys = []
# I used a with context manager to ensure file.close()
with open('data.txt') as f: 
    while True: 
        # read the current pointer and store it into the keys list
        pos = f.tell()
        keys.append(pos)
        # now I check if there is some data left, if not then break
        data = f.readline() 
        if not data: 
            break 

this way stores the final (trailing) pos as well if you only want the start of a row, use this

# list to store results.
keys = []
# I used a with context manager to ensure file.close()
with open('data.txt') as f: 
    while True: 
        # read the current pointer and store it into the keys list
        pos = f.tell()
        # now I check if there is some data left, if not then break
        data = f.readline() 
        if not data: 
            break
        # if we didn't break then we store the pos
        keys.append(pos)

Upvotes: 1

ruohola
ruohola

Reputation: 24038

You didn't add the first pointer to the key list (you have 2x pos = op.tell() before you do the first key.append(pos)).

You should just remove the 2nd and 3rd lines:

op = open('data.txt', 'r')
key = []
while data:
    pos = op.tell()
    data = op.readline()
    key.append(pos)

Upvotes: 1

Related Questions