为什么python中的seek返回None?

3 投票
2 回答
1700 浏览
提问于 2025-04-18 07:44

这个文档上说得很清楚:

返回新的绝对位置。

但是,seek 似乎返回的是 None(在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. 这是一个已知的bug吗?
  2. 这是文档的问题还是实现的问题?

2 个回答

1

接着Martjin的回答,使用 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'>

通过检查对象的类型,你会发现变量 f 不是属于 io 的,而是属于 file 的,所以你需要查找的文档会有所不同。

10

你看错文档了。使用Python 2的时候,你需要查看file.seek()这个部分:

这个方法没有返回值。

使用io.open()是可以的,如果你这样做,你会得到一个不同的对象,这个对象的seek()方法返回当前的位置:

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'>

io模块是Python 3的新输入输出架构,在Python 2中也可以使用。Python 3的内置open()函数io.open()的别名,但在Python 2中还不是。

撰写回答