概述
seek() 该方法用于将指针读取到指定位置的移动文件。
语法
seek() 方法语法如下:
fileObject.seek(offset[,whence])
参数
offset -- 开始偏移,即需要移动偏移的字节数
whence:可选,默认值为 0.定义offset参数意味着从哪个位置偏移;0代表从文件开始,1代表从当前位置开始,2代表从文件结束开始。
file.seek(off, whence=0):
将off操作标记(文件指针)从文件中移动,向结束方向移动,向负开始方向移动。
如果设置了whence参数,则以whence设置的起始位置为准,0代表从头开始,1代表当前位置,2代表文件的末尾位置。
#!/usr/bin/python #-*-coding:utf-8-*- #文件定位测试 #打开文件 fo=open("foo.txt","r+") allstr=fo.read() print"全部内容:\n",allstr print"当前指针位置:",fo.tell() print35*"=" #指针调整到开始 position=fo.seek(0,0) str=fo.read(3) print"读取前三个字符串:",str #找到当前的位置 position=fo.tell() print"当前指针位置:",position print35*"=" #将指针重新定位到当前位置开始 position=fo.seek(2,1) print"前一个指针移动2个,现在的位置:",fo.tell() a=fo.read(2) print"从指针位置读取两个字符:",a print"当前指针位置:",fo.tell() print35*"=" #将指针重新定位到从末端开始 position=fo.seek(-3,2) print"从末尾倒数三个,指针位置如下:",fo.tell() a=fo.read() print"从指针位置读取字符串:",a print"当前指针位置:",fo.tell() #关闭打开的文件 fo.close
foo.txt内容如下:weiruoyu
输出结果如下:
全部内容: weiruoyu 当前指针位置:8 =================================== 读取前三个字符串:wei 当前指针位置:3 =================================== 上一个指针移动2个,现在的位置:5 从指针位置读取两个字符:oy 当前指针位置:7 =================================== 从末尾倒数3个,指针位置为:5 从指针位置读取字符串:oyu 当前指针位置:8
python学习网,大量免费python视频教程,欢迎在线学习!