Solving Python’s OSError: telling position disabled by next() call

OSError: telling position disabled by next() call is an error which happens when you do not use file.tell() properly.

In this article I am going to explain what happens when you get this error and how you can solve it with a main solution, we will also explore other solutions which can possibly solve the issue.

Exploring OSError: telling position disabled by next() call

The error occurs when file.tell() is not used properly.

First you need to pay attention to how the error looks like, the error should match or at least be very similar to this one.

                                                                       #
OSError: telling position disabled by next() call
                                                                       #

To solve the problem above, I have many solutions which have worked for me, bellow is a detailed explanation of the solutions.

Solution 1 : use a dedicated variable.

The first solution is to use a variable dedicated to store the position as you are iterating over the file.

                                                                       #
position = 0
with open('file.txt', 'rb') as f:
for line in f:
# process line
position += len(line)
                                                                       #

As you can see in the code above, this technique is a great alternative to file.tell() as you will always track of the position.

If this fix has not solved your problem you can check out the solution bellow.

Solution 2 : use f.tell() to return the position of the next line.

The second solution is to use f.tell() to return the position of the next line. Instead of use it the way that causes the error to happen.

So the code bellow.

                                                                       #
with open(path, "r+") as f:
for line in f:
f.tell() #OSError
                                                                       #

Should be replaced with the following code.

                                                                       #
with open(path, mode) as f:
line = f.readline()
while line:
f.tell()
line = f.readline()
                                                                       #

I hope these solutions helped you overcome your problem.

I hope the fix above fixed your problem, good luck with the scripts to come.

Summing-up

We arrived at the end of this quest to solve this annoying error, I hope me sharing my experience with you helped, I hope the other solutions helped, If you like this website support us on Kofi and keep browsing, thank you and good luck with your Python Journey, Cheers.

If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/