Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does seek return None in python?

Tags:

python

seek

The doc clearly says:

Return the new absolute position.

However, seek appears to return None (same behavior also on Linux):

Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> >>> >>> import os
>>> f=open("......","r")
>>> f.readline()
'......\n'
>>> f.tell()
44
>>> f.seek(0,2)
>>> f.tell()
9636
  1. Is this a know bug?
  2. Is this a doc or implementation bug?
like image 834
sds Avatar asked Sep 17 '26 17:09

sds


2 Answers

You are reading the wrong documentation. You need to look at file.seek() when using Python 2:

There is no return value.

Using io.open() is fine, and if you do, you'll get a different object, whose seek() method does return the current position:

Python 2.7.6 (default, Apr 28 2014, 17:17:35) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
>>> f = io.open('data.json')
>>> f.seek(0, 2)
39L
>>> type(f)
<type '_io.TextIOWrapper'>
>>> f = open('data.json')
>>> f.seek(0, 2)
>>> type(f)
<type 'file'>

The io module is the new I/O architecture for Python 3, available in Python 2 as well. The Python 3 built-in open() function is an alias for io.open(), but not yet so in Python 2.

like image 53
Martijn Pieters Avatar answered Sep 20 '26 05:09

Martijn Pieters


Following up on Martjin's answer, use type() to inspect the variable's type:

Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("foo", "r")
>>> type(f)
<type 'file'>

By inspecting the object type, you will see that the variable f is not a member of io, but of file, and so the documentation to look up would be different.

like image 27
Alex Reynolds Avatar answered Sep 20 '26 07:09

Alex Reynolds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!