file.seek(off, whence=0):

从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。

如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。

概述

seek() 方法用于移动文件读取指针到指定位置。

语法

seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

offset -- 开始的偏移量,也就是代表需要移动偏移的字节数

whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起

#!/usr/bin/python
# -*- coding: utf-8 -*-
# 文件定位测试
# 打开一个文件
fo = open("foo.txt", "r+")
allstr = fo.read()
print "全部内容:\n", allstr
print "当前指针位置: ", fo.tell()
print 35*"="
# 指针调到开始
position = fo.seek(0, 0)
str = fo.read(3)
print "读取前三个字符串是:", str
# 查找当前位置
position = fo.tell()
print "当前指针位置: ", position
print 35*"="
# 把指针再次重新定位到当前位置开始
position = fo.seek(2, 1)
print "上一个指针移动2个,现在位置: ", fo.tell()
a = fo.read(2)
print "从指针位置读取2个字符为: ", a
print "当前指针位置: ", fo.tell()
print 35*"="
# 把指针再次重新定位到从末尾开始
position = fo.seek(-3, 2)
print "从末尾倒数3个,指针位置为: ", fo.tell()
a = fo.read()
print "从指针位置读取字符串: ", a
print "当前指针位置: ", fo.tell()
# 关闭打开的文件
fo.close
foo.txt内容为:weiruoyu

输出结果为:

全部内容:

weiruoyu

当前指针位置: 8

===================================

读取前三个字符串是: wei

当前指针位置: 3

===================================

上一个指针移动2个,现在位置: 5

从指针位置读取2个字符为: oy

当前指针位置: 7

===================================

从末尾倒数3个,指针位置为: 5

从指针位置读取字符串: oyu

当前指针位置: 8

看明白上面的例子,就理解了。